Connections

This document describes how to access the underlying connection object (BaseDBAsyncClient) for the aliases defined as part of the DB config passed to the Tortoise.init call.

Below is a simple code snippet which shows how the interface can be accessed:

# connections is a singleton instance of the ConnectionHandler class and serves as the
# entrypoint to access all connection management APIs.
from tortoise import connections


# Assume that this is the Tortoise configuration used
await Tortoise.init(
    {
        "connections": {
            "default": {
                "engine": "tortoise.backends.sqlite",
                "credentials": {"file_path": "example.sqlite3"},
            }
        },
        "apps": {
            "events": {"models": ["__main__"], "default_connection": "default"}
        },
    }
)

conn: BaseDBAsyncClient = connections.get("default")
try:
    await conn.execute_query('SELECT * FROM "event"')
except OperationalError:
    print("Expected it to fail")

Important

The tortoise.connection.ConnectionHandler class has been implemented with the singleton pattern in mind and so when the ORM initializes, a singleton instance of this class tortoise.connection.connections is created automatically and lives in memory up until the lifetime of the app. Any attempt to modify or override its behaviour at runtime is risky and not recommended.

Please refer to this example for a detailed demonstration of how this API can be used in practice.

API Reference

class tortoise.connection.ConnectionHandler[source]
all()[source]

Returns a list of connection objects from the storage in the current context.

Return type:

List[BaseDBAsyncClient]

async close_all(discard=True)[source]

Closes all connections in the storage in the current context.

All closed connections will be removed from the storage by default.

Parameters:
discard=True

If False, all connection objects are closed but retained in the storage.

Return type:

None

property db_config : DBConfigType

Return the DB config.

This is the same config passed to the Tortoise.init method while initialization.

Raises:

ConfigurationError – If this property is accessed before calling the Tortoise.init method.

Return type:

DBConfigType

discard(conn_alias)[source]

Discards the given alias from the storage in the current context.

Parameters:
conn_alias

The alias for which the connection object should be discarded.

Important

Make sure to have called conn.close() for the provided alias before calling this method else there would be a connection leak (dangling connection).

Return type:

Optional[BaseDBAsyncClient]

get(conn_alias)[source]

Return the connection object for the given alias, creating it if needed.

Used for accessing the low-level connection object (BaseDBAsyncClient) for the given alias.

Parameters:
conn_alias

The alias for which the connection has to be fetched

Raises:

ConfigurationError – If the connection alias does not exist.

Return type:

BaseDBAsyncClient

reset(token)[source]

Reset the underlying storage to the previous context state.

Resets the storage state to the context associated with the provided token. After resetting storage state, any additional connections created in the old context are copied into the current context.

Parameters:
token

The token corresponding to the context to which the storage state has to be reset. Typically, this token is obtained by calling the set method of this class.

Return type:

None

set(conn_alias, conn_obj)[source]

Sets the given alias to the provided connection object.

Parameters:
conn_alias

The alias to set the connection for.

conn_obj

The connection object that needs to be set for this alias.

Note

This method copies the storage from the current context, updates the conn_alias with the provided conn_obj and sets the updated storage in a new context and therefore returns a contextvars.Token in order to restore the original context storage.

Return type:

Token