Session Creation / Deletion#

Outside of the admin APIs, all work with actual table data in a database occurs in the context of a session.

Session Factory#

To create a Session object:

session = database.session()

Create a new Session#

After creating the session object, use its create() method to trigger its creation on the server:

session.create()

Test for the existence of a Session#

After creating the session object, use its exists() method to determine whether the session still exists on the server:

assert session.exists()

Delete a Session#

Once done with the session object, use its delete() method to free up its resources on the server:

session.delete()

Using a Session as a Context Manager#

Rather than calling the Session’s create() and delete() methods directly, you can use the session as a Python context manager:

with database.session() as session:

    assert session.exists()
    # perform session operations here

Note

At the beginning of the with block, the session’s create() method is called. At the end of the with block, the session’s delete() method is called.

Next Step#

Next, learn about Implicit Transactions.