class documentation

class AsyncSession(ReversibleProxy):

View In Hierarchy

Asyncio version of _orm.Session.

The _asyncio.AsyncSession is a proxy for a traditional _orm.Session instance.

New in version 1.4.

To use an _asyncio.AsyncSession with custom _orm.Session implementations, see the :paramref:`_asyncio.AsyncSession.sync_session_class` parameter.

Async Class Method close​_all Close all _asyncio.AsyncSession sessions.
Async Method __aenter__ Undocumented
Async Method __aexit__ Undocumented
Method __init__ Construct a new _asyncio.AsyncSession.
Method ​_maker​_context​_manager Undocumented
Method begin Return an _asyncio.AsyncSessionTransaction object.
Method begin​_nested Return an _asyncio.AsyncSessionTransaction object which will begin a "nested" transaction, e.g. SAVEPOINT.
Async Method close Close out the transactional resources and ORM objects used by this _asyncio.AsyncSession.
Async Method commit Commit the current transaction in progress.
Async Method connection Return a _asyncio.AsyncConnection object corresponding to this .Session object's transactional state.
Async Method delete Mark an instance as deleted.
Async Method execute Execute a statement and return a buffered _engine.Result object.
Async Method flush Flush all the object changes to the database.
Async Method get Return an instance based on the given primary key identifier, or None if not found.
Method get​_bind Return a "bind" to which the synchronous proxied _orm.Session is bound.
Method get​_nested​_transaction Return the current nested transaction in progress, if any.
Method get​_transaction Return the current root transaction in progress, if any.
Async Method invalidate Close this Session, using connection invalidation.
Async Method merge Copy the state of a given instance into a corresponding instance within this _asyncio.AsyncSession.
Async Method refresh Expire and refresh the attributes on the given instance.
Async Method rollback Rollback the current transaction in progress.
Async Method run​_sync Invoke the given sync callable passing sync self as the first argument.
Async Method scalar Execute a statement and return a scalar result.
Async Method scalars Execute a statement and return scalar results.
Async Method stream Execute a statement and return a streaming _asyncio.AsyncResult object.
Async Method stream​_scalars Execute a statement and return a stream of scalar results.
Class Variable ​_is​_asyncio Undocumented
Class Variable dispatch Undocumented
Instance Variable ​_proxied Undocumented
Instance Variable bind Undocumented
Instance Variable binds Undocumented
Instance Variable sync​_session Reference to the underlying _orm.Session this _asyncio.AsyncSession proxies requests towards.
Instance Variable sync​_session​_class The class or callable that provides the underlying _orm.Session instance for a particular _asyncio.AsyncSession.

Inherited from ReversibleProxy:

Class Method ​_regenerate​_proxy​_for​_target Undocumented
Class Method ​_retrieve​_proxy​_for​_target Undocumented
Class Method ​_target​_gced Undocumented
Method ​_assign​_proxied Undocumented
Class Variable __slots__ Undocumented
Class Variable ​_proxy​_objects Undocumented
@classmethod
async def close_all(self):
Close all _asyncio.AsyncSession sessions.
async def __aenter__(self):

Undocumented

async def __aexit__(self, type_, value, traceback):

Undocumented

def __init__(self, bind=None, binds=None, sync_session_class=None, **kw):

Construct a new _asyncio.AsyncSession.

All parameters other than sync_session_class are passed to the sync_session_class callable directly to instantiate a new _orm.Session. Refer to _orm.Session.__init__ for parameter documentation.

Parameters
bindUndocumented
bindsUndocumented
sync​_session​_class

A _orm.Session subclass or other callable which will be used to construct the _orm.Session which will be proxied. This parameter may be used to provide custom _orm.Session subclasses. Defaults to the _asyncio.AsyncSession.sync_session_class class-level attribute.

New in version 1.4.24.
**kwUndocumented
def _maker_context_manager(self):

Undocumented

def begin(self, **kw):

Return an _asyncio.AsyncSessionTransaction object.

The underlying _orm.Session will perform the "begin" action when the _asyncio.AsyncSessionTransaction object is entered:

async with async_session.begin():
    # .. ORM transaction is begun

Note that database IO will not normally occur when the session-level transaction is begun, as database transactions begin on an on-demand basis. However, the begin block is async to accommodate for a _orm.SessionEvents.after_transaction_create event hook that may perform IO.

For a general description of ORM begin, see _orm.Session.begin.

def begin_nested(self, **kw):

Return an _asyncio.AsyncSessionTransaction object which will begin a "nested" transaction, e.g. SAVEPOINT.

Behavior is the same as that of _asyncio.AsyncSession.begin.

For a general description of ORM begin nested, see _orm.Session.begin_nested.

async def close(self):

Close out the transactional resources and ORM objects used by this _asyncio.AsyncSession.

This expunges all ORM objects associated with this _asyncio.AsyncSession, ends any transaction in progress and :term:`releases` any _asyncio.AsyncConnection objects which this _asyncio.AsyncSession itself has checked out from associated _asyncio.AsyncEngine objects. The operation then leaves the _asyncio.AsyncSession in a state which it may be used again.

Tip

The _asyncio.AsyncSession.close method does not prevent the Session from being used again. The _asyncio.AsyncSession itself does not actually have a distinct "closed" state; it merely means the _asyncio.AsyncSession will release all database connections and ORM objects.

See Also

:ref:`session_closing` - detail on the semantics of _asyncio.AsyncSession.close

async def commit(self):
Commit the current transaction in progress.
async def connection(self, **kw):

Return a _asyncio.AsyncConnection object corresponding to this .Session object's transactional state.

This method may also be used to establish execution options for the database connection used by the current transaction.

New in version 1.4.24: Added **kw arguments which are passed through to the underlying _orm.Session.connection method.

See Also

_orm.Session.connection - main documentation for "connection"

async def delete(self, instance):

Mark an instance as deleted.

The database delete operation occurs upon flush().

As this operation may need to cascade along unloaded relationships, it is awaitable to allow for those queries to take place.

See Also

_orm.Session.delete - main documentation for delete

async def execute(self, statement, params=None, execution_options=util.EMPTY_DICT, bind_arguments=None, **kw):

Execute a statement and return a buffered _engine.Result object.

See Also

_orm.Session.execute - main documentation for execute

async def flush(self, objects=None):

Flush all the object changes to the database.

See Also

_orm.Session.flush - main documentation for flush

async def get(self, entity, ident, options=None, populate_existing=False, with_for_update=None, identity_token=None):

Return an instance based on the given primary key identifier, or None if not found.

See Also

_orm.Session.get - main documentation for get

def get_bind(self, mapper=None, clause=None, bind=None, **kw):

Return a "bind" to which the synchronous proxied _orm.Session is bound.

Unlike the _orm.Session.get_bind method, this method is currently not used by this .AsyncSession in any way in order to resolve engines for requests.

Note

This method proxies directly to the _orm.Session.get_bind method, however is currently not useful as an override target, in contrast to that of the _orm.Session.get_bind method. The example below illustrates how to implement custom _orm.Session.get_bind schemes that work with .AsyncSession and .AsyncEngine.

The pattern introduced at :ref:`session_custom_partitioning` illustrates how to apply a custom bind-lookup scheme to a _orm.Session given a set of _engine.Engine objects. To apply a corresponding _orm.Session.get_bind implementation for use with a .AsyncSession and .AsyncEngine objects, continue to subclass _orm.Session and apply it to .AsyncSession using :paramref:`.AsyncSession.sync_session_class`. The inner method must continue to return _engine.Engine instances, which can be acquired from a _asyncio.AsyncEngine using the _asyncio.AsyncEngine.sync_engine attribute:

# using example from "Custom Vertical Partitioning"


import random

from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.orm import Session, sessionmaker

# construct async engines w/ async drivers
engines = {
    'leader':create_async_engine("sqlite+aiosqlite:///leader.db"),
    'other':create_async_engine("sqlite+aiosqlite:///other.db"),
    'follower1':create_async_engine("sqlite+aiosqlite:///follower1.db"),
    'follower2':create_async_engine("sqlite+aiosqlite:///follower2.db"),
}

class RoutingSession(Session):
    def get_bind(self, mapper=None, clause=None, **kw):
        # within get_bind(), return sync engines
        if mapper and issubclass(mapper.class_, MyOtherClass):
            return engines['other'].sync_engine
        elif self._flushing or isinstance(clause, (Update, Delete)):
            return engines['leader'].sync_engine
        else:
            return engines[
                random.choice(['follower1','follower2'])
            ].sync_engine

# apply to AsyncSession using sync_session_class
AsyncSessionMaker = sessionmaker(
    class_=AsyncSession,
    sync_session_class=RoutingSession
)

The _orm.Session.get_bind method is called in a non-asyncio, implicitly non-blocking context in the same manner as ORM event hooks and functions that are invoked via .AsyncSession.run_sync, so routines that wish to run SQL commands inside of _orm.Session.get_bind can continue to do so using blocking-style code, which will be translated to implicitly async calls at the point of invoking IO on the database drivers.

def get_nested_transaction(self):

Return the current nested transaction in progress, if any.

New in version 1.4.18.
Returns
an _asyncio.AsyncSessionTransaction object, or None.
def get_transaction(self):

Return the current root transaction in progress, if any.

New in version 1.4.18.
Returns
an _asyncio.AsyncSessionTransaction object, or None.
async def invalidate(self):

Close this Session, using connection invalidation.

For a complete description, see _orm.Session.invalidate.

async def merge(self, instance, load=True, options=None):

Copy the state of a given instance into a corresponding instance within this _asyncio.AsyncSession.

See Also

_orm.Session.merge - main documentation for merge

async def refresh(self, instance, attribute_names=None, with_for_update=None):

Expire and refresh the attributes on the given instance.

A query will be issued to the database and all attributes will be refreshed with their current database value.

This is the async version of the _orm.Session.refresh method. See that method for a complete description of all options.

See Also

_orm.Session.refresh - main documentation for refresh

async def rollback(self):
Rollback the current transaction in progress.
async def run_sync(self, fn, *arg, **kw):

Invoke the given sync callable passing sync self as the first argument.

This method maintains the asyncio event loop all the way through to the database connection by running the given callable in a specially instrumented greenlet.

E.g.:

with AsyncSession(async_engine) as session:
    await session.run_sync(some_business_method)

Note

The provided callable is invoked inline within the asyncio event loop, and will block on traditional IO calls. IO within this callable should only call into SQLAlchemy's asyncio database APIs which will be properly adapted to the greenlet context.

async def scalar(self, statement, params=None, execution_options=util.EMPTY_DICT, bind_arguments=None, **kw):

Execute a statement and return a scalar result.

See Also

_orm.Session.scalar - main documentation for scalar

async def scalars(self, statement, params=None, execution_options=util.EMPTY_DICT, bind_arguments=None, **kw):

Execute a statement and return scalar results.

New in version 1.4.24.

See Also

_orm.Session.scalars - main documentation for scalars

_asyncio.AsyncSession.stream_scalars - streaming version

Returns
a _result.ScalarResult object
async def stream(self, statement, params=None, execution_options=util.EMPTY_DICT, bind_arguments=None, **kw):
Execute a statement and return a streaming _asyncio.AsyncResult object.
async def stream_scalars(self, statement, params=None, execution_options=util.EMPTY_DICT, bind_arguments=None, **kw):

Execute a statement and return a stream of scalar results.

New in version 1.4.24.

See Also

_orm.Session.scalars - main documentation for scalars

_asyncio.AsyncSession.scalars - non streaming version

Returns
an _asyncio.AsyncScalarResult object
_is_asyncio: bool =

Undocumented

dispatch =

Undocumented

_proxied =

Undocumented

bind =

Undocumented

binds =

Undocumented

sync_session: Session =

Reference to the underlying _orm.Session this _asyncio.AsyncSession proxies requests towards.

This instance can be used as an event target.

sync_session_class =

The class or callable that provides the underlying _orm.Session instance for a particular _asyncio.AsyncSession.

At the class level, this attribute is the default value for the :paramref:`_asyncio.AsyncSession.sync_session_class` parameter. Custom subclasses of _asyncio.AsyncSession can override this.

At the instance level, this attribute indicates the current class or callable that was used to provide the _orm.Session instance for this _asyncio.AsyncSession instance.

New in version 1.4.24.