Contextual/Thread-local Sessions

    SQLAlchemy includes its own helper object, which helps with the establishment of user-defined Session scopes. It is also used by third-party integration systems to help construct their integration schemes.

    The object is the object, and it represents a registry of Session objects. If you’re not familiar with the registry pattern, a good introduction can be found in .

    Warning

    The scoped_session registry by default uses a Python in order to track instances. This is not necessarily compatible with all application servers, particularly those which make use of greenlets or other alternative forms of concurrency control, which may lead to race conditions (e.g. randomly occurring failures) when used in moderate to high concurrency scenarios. Please read Thread-Local Scope and below to more fully understand the implications of using threading.local() to track Session objects and consider more explicit means of scoping when using application servers which are not based on traditional threads.

    Note

    The object is a very popular and useful object used by many SQLAlchemy applications. However, it is important to note that it presents only one approach to the issue of Session management. If you’re new to SQLAlchemy, and especially if the term “thread-local variable” seems strange to you, we recommend that if possible you familiarize first with an off-the-shelf integration system such as or zope.sqlalchemy.

    A is constructed by calling it, passing it a factory which can create new Session objects. A factory is just something that produces a new object when called, and in the case of , the most common factory is the sessionmaker, introduced earlier in this section. Below we illustrate this usage:

    The object we’ve created will now call upon the sessionmaker when we “call” the registry:

    1. >>> some_session = Session()

    Above, some_session is an instance of , which we can now use to talk to the database. This same Session is also present within the registry we’ve created. If we call upon the registry a second time, we get back the same Session:

    1. >>> some_other_session = Session()
    2. >>> some_session is some_other_session
    3. True

    This pattern allows disparate sections of the application to call upon a global , so that all those areas may share the same session without the need to pass it explicitly. The Session we’ve established in our registry will remain, until we explicitly tell our registry to dispose of it, by calling :

    1. >>> Session.remove()

    The scoped_session.remove() method first calls on the current Session, which has the effect of releasing any connection/transactional resources owned by the first, then discarding the Session itself. “Releasing” here means that connections are returned to their connection pool and any transactional state is rolled back, ultimately using the rollback() method of the underlying DBAPI connection.

    At this point, the object is “empty”, and will create a new Session when called again. As illustrated below, this is not the same we had before:

    1. >>> new_session = Session()
    2. >>> new_session is some_session
    3. False

    The above series of steps illustrates the idea of the “registry” pattern in a nutshell. With that basic idea in hand, we can discuss some of the details of how this pattern proceeds.

    The job of the is simple; hold onto a Session for all who ask for it. As a means of producing more transparent access to this , the scoped_session also includes proxy behavior, meaning that the registry itself can be treated just like a directly; when methods are called on this object, they are proxied to the underlying Session being maintained by the registry:

    1. Session = scoped_session(some_factory)
    2. # equivalent to:
    3. #
    4. # session = Session()
    5. # print(session.scalars(select(MyClass)).all())
    6. #
    7. print(Session.scalars(select(MyClass)).all())

    The above code accomplishes the same task as that of acquiring the current by calling upon the registry, then using that Session.

    Users who are familiar with multithreaded programming will note that representing anything as a global variable is usually a bad idea, as it implies that the global object will be accessed by many threads concurrently. The Session object is entirely designed to be used in a non-concurrent fashion, which in terms of multithreading means “only in one thread at a time”. So our above example of usage, where the same Session object is maintained across multiple calls, suggests that some process needs to be in place such that multiple calls across many threads don’t actually get a handle to the same session. We call this notion thread local storage, which means, a special object is used that will maintain a distinct object per each application thread. Python provides this via the construct. The scoped_session object by default uses this object as storage, so that a single is maintained for all who call upon the scoped_session registry, but only within the scope of a single thread. Callers who call upon the registry in a different thread get a instance that is local to that other thread.

    Using this technique, the scoped_session provides a quick and relatively simple (if one is familiar with thread-local storage) way of providing a single, global object in an application that is safe to be called upon from multiple threads.

    The method, as always, removes the current Session associated with the thread, if any. However, one advantage of the threading.local() object is that if the application thread itself ends, the “storage” for that thread is also garbage collected. So it is in fact “safe” to use thread local scope with an application that spawns and tears down threads, without the need to call . However, the scope of transactions themselves, i.e. ending them via Session.commit() or , will usually still be something that must be explicitly arranged for at the appropriate time, unless the application actually ties the lifespan of a thread to the lifespan of a transaction.

    As discussed in the section , a web application is architected around the concept of a web request, and integrating such an application with the Session usually implies that the will be associated with that request. As it turns out, most Python web frameworks, with notable exceptions such as the asynchronous frameworks Twisted and Tornado, use threads in a simple way, such that a particular web request is received, processed, and completed within the scope of a single worker thread. When the request ends, the worker thread is released to a pool of workers where it is available to handle another request.

    This simple correspondence of web request and thread means that to associate a Session with a thread implies it is also associated with the web request running within that thread, and vice versa, provided that the is created only after the web request begins and torn down just before the web request ends. So it is a common practice to use scoped_session as a quick way to integrate the with a web application. The sequence diagram below illustrates this flow:

    1. Web Server Web Framework SQLAlchemy ORM Code
    2. -------------- -------------- ------------------------------
    3. startup -> Web framework # Session registry is established
    4. initializes Session = scoped_session(sessionmaker())
    5. incoming
    6. web request -> web request -> # The registry is *optionally*
    7. starts # called upon explicitly to create
    8. # a Session local to the thread and/or request
    9. Session()
    10. # the Session registry can otherwise
    11. # be used at any time, creating the
    12. # request-local Session() if not present,
    13. # or returning the existing one
    14. Session.execute(select(MyClass)) # ...
    15. Session.add(some_object) # ...
    16. # if data was modified, commit the
    17. # transaction
    18. Session.commit()
    19. web request ends -> # the registry is instructed to
    20. # remove the Session
    21. Session.remove()
    22. sends output <-
    23. outgoing web <-
    24. response

    Using the above flow, the process of integrating the Session with the web application has exactly two requirements:

    1. Create a single registry when the web application first starts, ensuring that this object is accessible by the rest of the application.

    2. Ensure that scoped_session.remove() is called when the web request ends, usually by integrating with the web framework’s event system to establish an “on request end” event.

    As noted earlier, the above pattern is just one potential way to integrate a with a web framework, one which in particular makes the significant assumption that the web framework associates web requests with application threads. It is however strongly recommended that the integration tools provided with the web framework itself be used, if available, instead of scoped_session.

    In particular, while using a thread local can be convenient, it is preferable that the be associated directly with the request, rather than with the current thread. The next section on custom scopes details a more advanced configuration which can combine the usage of scoped_session with direct request based scope, or any kind of scope.

    The scoped_session object’s default behavior of “thread local” scope is only one of many options on how to “scope” a . A custom scope can be defined based on any existing system of getting at “the current thing we are working with”.

    Suppose a web framework defines a library function get_current_request(). An application built using this framework can call this function at any time, and the result will be some kind of Request object that represents the current request being processed. If the Request object is hashable, then this function can be easily integrated with scoped_session to associate the with the request. Below we illustrate this in conjunction with a hypothetical event marker provided by the web framework on_request_end, which allows code to be invoked whenever a request ends:

    1. from my_web_framework import get_current_request, on_request_end
    2. from sqlalchemy.orm import scoped_session, sessionmaker
    3. Session = scoped_session(sessionmaker(bind=some_engine), scopefunc=get_current_request)
    4. @on_request_end
    5. def remove_session(req):

    Above, we instantiate scoped_session in the usual way, except that we pass our request-returning function as the “scopefunc”. This instructs to use this function to generate a dictionary key whenever the registry is called upon to return the current Session. In this case it is particularly important that we ensure a reliable “remove” system is implemented, as this dictionary is not otherwise self-managed.

    class sqlalchemy.orm.scoping.scoped_session

    Provides scoped management of Session objects.

    See for a tutorial.

    Note

    When using Asynchronous I/O (asyncio), the async-compatible class should be used in place of scoped_session.

    Members

    , __init__(), , add_all(), , begin(), , bind, , bulk_save_objects(), , close(), , commit(), , connection(), , deleted, , execute(), , expire_all(), , expunge_all(), , get(), , identity_key(), , info, , is_modified(), , new, , object_session(), , query_property(), , remove(), , scalar(), , session_factory

    Class signature

    class (typing.Generic)

    • method sqlalchemy.orm.scoping.scoped_session.__call__(**kw: Any) → _S

      Return the current , creating it using the scoped_session.session_factory if not present.

      • Parameters:

        **kw – Keyword arguments will be passed to the callable, if an existing Session is not present. If the is present and keyword arguments have been passed, InvalidRequestError is raised.

    • method __init__(session_factory: sessionmaker[_S], scopefunc: Optional[Callable[[], Any]] = None)

      Construct a new .

      • Parameters:

        • session_factory – a factory to create new Session instances. This is usually, but not necessarily, an instance of .

        • scopefunc – optional function which defines the current scope. If not passed, the scoped_session object assumes “thread-local” scope, and will use a Python threading.local() in order to maintain the current . If passed, the function should return a hashable token; this token will be used as the key in a dictionary in order to store and retrieve the current Session.

    • method add(instance: object, _warn: bool = True) → None

      Place an object into this Session.

      Proxied for the class on behalf of the scoped_session class.

      Objects that are in the state when passed to the Session.add() method will move to the state, until the next flush, at which point they will move to the persistent state.

      Objects that are in the state when passed to the Session.add() method will move to the state directly.

      If the transaction used by the Session is rolled back, objects which were transient when they were passed to will be moved back to the transient state, and will no longer be present within this .

      See also

      Session.add_all()

      - at Basics of Using a Session

    • method add_all(instances: Iterable[object]) → None

      Add the given collection of instances to this Session.

      Proxied for the class on behalf of the scoped_session class.

      See the documentation for for a general behavioral description.

      See also

      Session.add()

      - at Basics of Using a Session

    • attribute autoflush

      Proxy for the Session.autoflush attribute on behalf of the scoped_session class.

    • method begin(nested: bool = False) → SessionTransaction

      Begin a transaction, or nested transaction, on this , if one is not already begun.

      Proxied for the Session class on behalf of the class.

      The Session object features autobegin behavior, so that normally it is not necessary to call the method explicitly. However, it may be used in order to control the scope of when the transactional state is begun.

      When used to begin the outermost transaction, an error is raised if this Session is already inside of a transaction.

      • Parameters:

        nested – if True, begins a SAVEPOINT transaction and is equivalent to calling . For documentation on SAVEPOINT transactions, please see Using SAVEPOINT.

        Returns:

        the object. Note that SessionTransaction acts as a Python context manager, allowing to be used in a “with” block. See Explicit Begin for an example.

      See also

      Managing Transactions

    • method sqlalchemy.orm.scoping.scoped_session.begin_nested() →

      Begin a “nested” transaction on this Session, e.g. SAVEPOINT.

      Proxied for the Session class on behalf of the class.

      The target database(s) and associated drivers must support SQL SAVEPOINT for this method to function correctly.

      For documentation on SAVEPOINT transactions, please see Using SAVEPOINT.

      See also

      Serializable isolation / Savepoints / Transactional DDL - special workarounds required with the SQLite driver in order for SAVEPOINT to work correctly.

    • attribute bind

      Proxy for the Session.bind attribute on behalf of the scoped_session class.

    • method bulk_insert_mappings(mapper: Mapper[Any], mappings: Iterable[Dict[str, Any]], return_defaults: bool = False, render_nulls: bool = False) → None

      Perform a bulk insert of the given list of mapping dictionaries.

      Proxied for the class on behalf of the scoped_session class.

      Legacy Feature

      This method is a legacy feature as of the 2.0 series of SQLAlchemy. For modern bulk INSERT and UPDATE, see the sections and ORM Bulk UPDATE by Primary Key. The 2.0 API shares implementation details with this method and adds new features as well.

      • Parameters:

        • mapper – a mapped class, or the actual object, representing the single kind of object represented within the mapping list.

        • mappings – a sequence of dictionaries, each one containing the state of the mapped row to be inserted, in terms of the attribute names on the mapped class. If the mapping refers to multiple tables, such as a joined-inheritance mapping, each dictionary must contain all keys to be populated into all tables.

        • return_defaults

          when True, the INSERT process will be altered to ensure that newly generated primary key values will be fetched. The rationale for this parameter is typically to enable Joined Table Inheritance mappings to be bulk inserted.

          Note

          for backends that don’t support RETURNING, the parameter can significantly decrease performance as INSERT statements can no longer be batched. See “Insert Many Values” Behavior for INSERT statements for background on which backends are affected.

        • render_nulls

          When True, a value of None will result in a NULL value being included in the INSERT statement, rather than the column being omitted from the INSERT. This allows all the rows being INSERTed to have the identical set of columns which allows the full set of rows to be batched to the DBAPI. Normally, each column-set that contains a different combination of NULL values than the previous row must omit a different series of columns from the rendered INSERT statement, which means it must be emitted as a separate statement. By passing this flag, the full set of rows are guaranteed to be batchable into one batch; the cost however is that server-side defaults which are invoked by an omitted column will be skipped, so care must be taken to ensure that these are not necessary.

          Warning

          When this flag is set, server side default SQL values will not be invoked for those columns that are inserted as NULL; the NULL value will be sent explicitly. Care must be taken to ensure that no server-side default functions need to be invoked for the operation as a whole.

    1. See also
    2. [ORM-Enabled INSERT, UPDATE, and DELETE statements]($8137f13cfe1f7fec.md)
    3. [Session.bulk\_insert\_mappings()]($694f628462946390.md#sqlalchemy.orm.Session.bulk_insert_mappings "sqlalchemy.orm.Session.bulk_insert_mappings")
    4. [Session.bulk\_update\_mappings()]($694f628462946390.md#sqlalchemy.orm.Session.bulk_update_mappings "sqlalchemy.orm.Session.bulk_update_mappings")
    • method bulk_update_mappings(mapper: Mapper[Any], mappings: Iterable[Dict[str, Any]]) → None

      Perform a bulk update of the given list of mapping dictionaries.

      Proxied for the class on behalf of the scoped_session class.

      Legacy Feature

      This method is a legacy feature as of the 2.0 series of SQLAlchemy. For modern bulk INSERT and UPDATE, see the sections and ORM Bulk UPDATE by Primary Key. The 2.0 API shares implementation details with this method and adds new features as well.

      • Parameters:

        • mapper – a mapped class, or the actual object, representing the single kind of object represented within the mapping list.

        • mappings – a sequence of dictionaries, each one containing the state of the mapped row to be updated, in terms of the attribute names on the mapped class. If the mapping refers to multiple tables, such as a joined-inheritance mapping, each dictionary may contain keys corresponding to all tables. All those keys which are present and are not part of the primary key are applied to the SET clause of the UPDATE statement; the primary key values, which are required, are applied to the WHERE clause.

    1. See also
    2. [ORM-Enabled INSERT, UPDATE, and DELETE statements]($8137f13cfe1f7fec.md)
    3. [Session.bulk\_insert\_mappings()]($694f628462946390.md#sqlalchemy.orm.Session.bulk_insert_mappings "sqlalchemy.orm.Session.bulk_insert_mappings")
    4. [Session.bulk\_save\_objects()]($694f628462946390.md#sqlalchemy.orm.Session.bulk_save_objects "sqlalchemy.orm.Session.bulk_save_objects")
    • method sqlalchemy.orm.scoping.scoped_session.close() → None

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

      Proxied for the Session class on behalf of the class.

      This expunges all ORM objects associated with this Session, ends any transaction in progress and any Connection objects which this itself has checked out from associated Engine objects. The operation then leaves the in a state which it may be used again.

      Tip

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

      See also

      - detail on the semantics of Session.close()

    • classmethod close_all() → None

      Close all sessions in memory.

      Proxied for the Session class on behalf of the class.

      Deprecated since version 1.3: The Session.close_all() method is deprecated and will be removed in a future release. Please refer to close_all_sessions().

    • method commit() → None

      Flush pending changes and commit the current transaction.

      Proxied for the Session class on behalf of the class.

      When the COMMIT operation is complete, all objects are fully expired, erasing their internal contents, which will be automatically re-loaded when the objects are next accessed. In the interim, these objects are in an expired state and will not function if they are from the Session. Additionally, this re-load operation is not supported when using asyncio-oriented APIs. The parameter may be used to disable this behavior.

      When there is no transaction in place for the Session, indicating that no operations were invoked on this since the previous call to Session.commit(), the method will begin and commit an internal-only “logical” transaction, that does not normally affect the database unless pending flush changes were detected, but will still invoke event handlers and object expiration rules.

      The outermost database transaction is committed unconditionally, automatically releasing any SAVEPOINTs in effect.

      See also

      Managing Transactions

    • method sqlalchemy.orm.scoping.scoped_session.configure(**kwargs: Any) → None

      reconfigure the used by this scoped_session.

      See .

    • method sqlalchemy.orm.scoping.scoped_session.connection(bind_arguments: Optional[_BindArguments] = None, execution_options: Optional[_ExecuteOptions] = None) →

      Return a Connection object corresponding to this object’s transactional state.

      Proxied for the Session class on behalf of the class.

      Either the Connection corresponding to the current transaction is returned, or if no transaction is in progress, a new one is begun and the returned (note that no transactional state is established with the DBAPI until the first SQL statement is emitted).

      Ambiguity in multi-bind or unbound Session objects can be resolved through any of the optional keyword arguments. This ultimately makes usage of the method for resolution.

      • Parameters:

        • bind_arguments – dictionary of bind arguments. May include “mapper”, “bind”, “clause”, other custom arguments that are passed to Session.get_bind().

        • execution_options

          a dictionary of execution options that will be passed to , when the connection is first procured only. If the connection is already present within the Session, a warning is emitted and the arguments are ignored.

          See also

    • method sqlalchemy.orm.scoping.scoped_session.delete(instance: object) → None

      Mark an instance as deleted.

      Proxied for the class on behalf of the scoped_session class.

      The object is assumed to be either or detached when passed; after the method is called, the object will remain in the state until the next flush proceeds. During this time, the object will also be a member of the Session.deleted collection.

      When the next flush proceeds, the object will move to the state, indicating a DELETE statement was emitted for its row within the current transaction. When the transaction is successfully committed, the deleted object is moved to the detached state and is no longer present within this .

      See also

      Deleting - at

    • attribute sqlalchemy.orm.scoping.scoped_session.deleted

      The set of all instances marked as ‘deleted’ within this Session

      Proxied for the class on behalf of the scoped_session class.

    • attribute dirty

      The set of all persistent instances considered dirty.

      Proxied for the Session class on behalf of the class.

      E.g.:

      1. some_mapped_object in session.dirty

      Instances are considered dirty when they were modified but not deleted.

      Note that this ‘dirty’ calculation is ‘optimistic’; most attribute-setting or collection modification operations will mark an instance as ‘dirty’ and place it in this set, even if there is no net change to the attribute’s value. At flush time, the value of each attribute is compared to its previously saved value, and if there’s no net change, no SQL operation will occur (this is a more expensive operation so it’s only done at flush time).

      To check if an instance has actionable net changes to its attributes, use the Session.is_modified() method.

    • method execute(statement: Executable, params: Optional[_CoreAnyExecuteParams] = None, *, execution_options: OrmExecuteOptionsParameter = {}, bind_arguments: Optional[_BindArguments] = None, _parent_execute_state: Optional[Any] = None, _add_event: Optional[Any] = None) → [Any]

      Execute a SQL expression construct.

      Proxied for the Session class on behalf of the class.

      Returns a Result object representing results of the statement execution.

      E.g.:

      1. from sqlalchemy import select
      2. result = session.execute(
      3. select(User).where(User.id == 5)
      4. )

      The API contract of is similar to that of Connection.execute(), the version of Connection.

      Changed in version 1.4: the method is now the primary point of ORM statement execution when using 2.0 style ORM usage.

      • Parameters:

        • statement – An executable statement (i.e. an expression such as select()).

        • params – Optional dictionary, or list of dictionaries, containing bound parameter values. If a single dictionary, single-row execution occurs; if a list of dictionaries, an “executemany” will be invoked. The keys in each dictionary must correspond to parameter names present in the statement.

        • execution_options

          optional dictionary of execution options, which will be associated with the statement execution. This dictionary can provide a subset of the options that are accepted by , and may also provide additional options understood only in an ORM context.

          See also

          ORM Execution Options - ORM-specific execution options

        • bind_arguments – dictionary of additional arguments to determine the bind. May include “mapper”, “bind”, or other custom arguments. Contents of this dictionary are passed to the method.

        Returns:

        a Result object.

    • method expire(instance: object, attribute_names: Optional[Iterable[str]] = None) → None

      Expire the attributes on an instance.

      Proxied for the Session class on behalf of the class.

      Marks the attributes of an instance as out of date. When an expired attribute is next accessed, a query will be issued to the Session object’s current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction.

      To expire all objects in the simultaneously, use Session.expire_all().

      The Session object’s default behavior is to expire all state whenever the Session.rollback() or Session.commit() methods are called, so that new state can be loaded for the new transaction. For this reason, calling Session.expire() only makes sense for the specific case that a non-ORM SQL statement was emitted in the current transaction.

      • Parameters:

        • instance – The instance to be refreshed.

        • attribute_names – optional list of string attribute names indicating a subset of attributes to be expired.

    1. See also
    2. [Refreshing / Expiring]($592600365cded3ff.md#session-expire) - introductory material
    3. [Session.expire()]($694f628462946390.md#sqlalchemy.orm.Session.expire "sqlalchemy.orm.Session.expire")
    4. [Session.refresh()]($694f628462946390.md#sqlalchemy.orm.Session.refresh "sqlalchemy.orm.Session.refresh")
    5. [Query.populate\_existing()]($3d0cc000ec6c7150.md#sqlalchemy.orm.Query.populate_existing "sqlalchemy.orm.Query.populate_existing")
    • method expire_all() → None

      Expires all persistent instances within this Session.

      Proxied for the Session class on behalf of the class.

      When any attributes on a persistent instance is next accessed, a query will be issued using the Session object’s current transactional context in order to load all expired attributes for the given instance. Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction.

      To expire individual objects and individual attributes on those objects, use Session.expire().

      The object’s default behavior is to expire all state whenever the Session.rollback() or Session.commit() methods are called, so that new state can be loaded for the new transaction. For this reason, calling Session.expire_all() is not usually needed, assuming the transaction is isolated.

      See also

      Refreshing / Expiring - introductory material

      Session.refresh()

    • method sqlalchemy.orm.scoping.scoped_session.expunge(instance: object) → None

      Remove the instance from this Session.

      Proxied for the class on behalf of the scoped_session class.

      This will free all internal references to the instance. Cascading will be applied according to the expunge cascade rule.

    • method expunge_all() → None

      Remove all object instances from this Session.

      Proxied for the Session class on behalf of the class.

      This is equivalent to calling expunge(obj) on all objects in this Session.

    • method sqlalchemy.orm.scoping.scoped_session.flush(objects: Optional[Sequence[Any]] = None) → None

      Flush all the object changes to the database.

      Proxied for the class on behalf of the scoped_session class.

      Writes out all pending object creations, deletions and modifications to the database as INSERTs, DELETEs, UPDATEs, etc. Operations are automatically ordered by the Session’s unit of work dependency solver.

      Database operations will be issued in the current transactional context and do not affect the state of the transaction, unless an error occurs, in which case the entire transaction is rolled back. You may flush() as often as you like within a transaction to move changes from Python to the database’s transaction buffer.

      • Parameters:

        objects

        Optional; restricts the flush operation to operate only on elements that are in the given collection.

        This feature is for an extremely narrow set of use cases where particular objects may need to be operated upon before the full flush() occurs. It is not intended for general use.

    • method get(entity: _EntityBindKey[_O], ident: _PKIdentityArgument, *, options: Optional[Sequence[ORMOption]] = None, populate_existing: bool = False, with_for_update: Optional[ForUpdateArg] = None, identity_token: Optional[Any] = None, execution_options: OrmExecuteOptionsParameter = {}, bind_arguments: Optional[_BindArguments] = None) → Optional[_O]

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

      Proxied for the class on behalf of the scoped_session class.

      E.g.:

      1. my_user = session.get(User, 5)
      2. some_object = session.get(VersionedFoo, (5, 10))
      3. some_object = session.get(
      4. VersionedFoo,
      5. {"id": 5, "version_id": 10}
      6. )

      New in version 1.4: Added , which is moved from the now legacy Query.get() method.

      is special in that it provides direct access to the identity map of the Session. If the given primary key identifier is present in the local identity map, the object is returned directly from this collection and no SQL is emitted, unless the object has been marked fully expired. If not present, a SELECT is performed in order to locate the object.

      also will perform a check if the object is present in the identity map and marked as expired - a SELECT is emitted to refresh the object as well as to ensure that the row is still present. If not, ObjectDeletedError is raised.

      • Parameters:

        • entity – a mapped class or indicating the type of entity to be loaded.

        • ident

          A scalar, tuple, or dictionary representing the primary key. For a composite (e.g. multiple column) primary key, a tuple or dictionary should be passed.

          For a single-column primary key, the scalar calling form is typically the most expedient. If the primary key of a row is the value “5”, the call looks like:

          1. my_object = session.get(SomeClass, 5)

          The tuple form contains primary key values typically in the order in which they correspond to the mapped Table object’s primary key columns, or if the configuration parameter were used, in the order used for that parameter. For example, if the primary key of a row is represented by the integer digits “5, 10” the call would look like:

          The dictionary form should include as keys the mapped attribute names corresponding to each element of the primary key. If the mapped class has the attributes id, as the attributes which store the object’s primary key value, the call would look like:

          1. my_object = session.get(SomeClass, {"id": 5, "version_id": 10})
        • options – optional sequence of loader options which will be applied to the query, if one is emitted.

        • populate_existing – causes the method to unconditionally emit a SQL query and refresh the object with the newly loaded data, regardless of whether or not the object is already present.

        • with_for_update – optional boolean True indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT; flags should match the parameters of Query.with_for_update(). Supersedes the parameter.

        • execution_options

          optional dictionary of execution options, which will be associated with the query execution if one is emitted. This dictionary can provide a subset of the options that are accepted by Connection.execution_options(), and may also provide additional options understood only in an ORM context.

          New in version 1.4.29.

          See also

          - ORM-specific execution options

        • bind_arguments

          dictionary of additional arguments to determine the bind. May include “mapper”, “bind”, or other custom arguments. Contents of this dictionary are passed to the Session.get_bind() method.

        Returns:

        The object instance, or None.

    1. See also
    2. [Partitioning Strategies (e.g. multiple database backends per Session)]($47efe01e33821e5c.md#session-partitioning)
    3. [Session.binds]($694f628462946390.md#sqlalchemy.orm.Session.params.binds "sqlalchemy.orm.Session")
    4. [Session.bind\_mapper()]($694f628462946390.md#sqlalchemy.orm.Session.bind_mapper "sqlalchemy.orm.Session.bind_mapper")
    5. [Session.bind\_table()]($694f628462946390.md#sqlalchemy.orm.Session.bind_table "sqlalchemy.orm.Session.bind_table")
    • classmethod identity_key(class\: Optional[Type[Any]] = None, _ident: Union[Any, Tuple[Any, …]] = None, *, instance: Optional[Any] = None, row: Optional[Union[[Any], RowMapping]] = None, identity_token: Optional[Any] = None) → _IdentityKeyType[Any]

      Return an identity key.

      Proxied for the class on behalf of the scoped_session class.

      This is an alias of .

    • attribute sqlalchemy.orm.scoping.scoped_session.identity_map

      Proxy for the attribute on behalf of the scoped_session class.

    • attribute info

      A user-modifiable dictionary.

      Proxied for the Session class on behalf of the class.

      The initial value of this dictionary can be populated using the info argument to the Session constructor or constructor or factory methods. The dictionary here is always local to this Session and can be modified independently of all other objects.

    • attribute sqlalchemy.orm.scoping.scoped_session.is_active

      True if this not in “partial rollback” state.

      Proxied for the Session class on behalf of the class.

      Changed in version 1.4: The Session no longer begins a new transaction immediately, so this attribute will be False when the is first instantiated.

      “partial rollback” state typically indicates that the flush process of the Session has failed, and that the method must be emitted in order to fully roll back the transaction.

      If this Session is not in a transaction at all, the will autobegin when it is first used, so in this case Session.is_active will return True.

      Otherwise, if this is within a transaction, and that transaction has not been rolled back internally, the Session.is_active will also return True.

      See also

      Session.in_transaction()

    • method is_modified(instance: object, include_collections: bool = True) → bool

      Return True if the given instance has locally modified attributes.

      Proxied for the Session class on behalf of the class.

      This method retrieves the history for each instrumented attribute on the instance and performs a comparison of the current value to its previously committed value, if any.

      It is in effect a more expensive and accurate version of checking for the given instance in the Session.dirty collection; a full test for each attribute’s net “dirty” status is performed.

      E.g.:

      1. return session.is_modified(someobject)

      A few caveats to this method apply:

      • Instances present in the collection may report False when tested with this method. This is because the object may have received change events via attribute mutation, thus placing it in Session.dirty, but ultimately the state is the same as that loaded from the database, resulting in no net change here.

      • Scalar attributes may not have recorded the previously set value when a new value was applied, if the attribute was not loaded, or was expired, at the time the new value was received - in these cases, the attribute is assumed to have a change, even if there is ultimately no net change against its database value. SQLAlchemy in most cases does not need the “old” value when a set event occurs, so it skips the expense of a SQL call if the old value isn’t present, based on the assumption that an UPDATE of the scalar value is usually needed, and in those few cases where it isn’t, is less expensive on average than issuing a defensive SELECT.

        The “old” value is fetched unconditionally upon set only if the attribute container has the active_history flag set to True. This flag is set typically for primary key attributes and scalar object references that are not a simple many-to-one. To set this flag for any arbitrary mapped column, use the active_history argument with .

      • Parameters:

        • instance – mapped instance to be tested for pending changes.

        • include_collections – Indicates if multivalued collections should be included in the operation. Setting this to False is a way to detect only local-column based properties (i.e. scalar columns or many-to-one foreign keys) that would result in an UPDATE for this instance upon flush.

    • method sqlalchemy.orm.scoping.scoped_session.merge(instance: _O, *, load: bool = True, options: Optional[[ORMOption]] = None) → _O

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

      Proxied for the class on behalf of the scoped_session class.

      examines the primary key attributes of the source instance, and attempts to reconcile it with an instance of the same primary key in the session. If not found locally, it attempts to load the object from the database based on primary key, and if none can be located, creates a new instance. The state of each attribute on the source instance is then copied to the target instance. The resulting target instance is then returned by the method; the original source instance is left unmodified, and un-associated with the Session if not already.

      This operation cascades to associated instances if the association is mapped with cascade="merge".

      See for a detailed discussion of merging.

      Changed in version 1.1: - Session.merge() will now reconcile pending objects with overlapping primary keys in the same way as persistent. See for discussion.

      • Parameters:

        • instance – Instance to be merged.

        • load

          Boolean, when False, merge() switches into a “high performance” mode which causes it to forego emitting history events as well as all database access. This flag is used for cases such as transferring graphs of objects into a from a second level cache, or to transfer just-loaded objects into the Session owned by a worker thread or process without re-querying the database.

          The load=False use case adds the caveat that the given object has to be in a “clean” state, that is, has no pending changes to be flushed - even if the incoming object is detached from any . This is so that when the merge operation populates local attributes and cascades to related objects and collections, the values can be “stamped” onto the target object as is, without generating any history or attribute events, and without the need to reconcile the incoming data with any existing related objects or collections that might not be loaded. The resulting objects from load=False are always produced as “clean”, so it is only appropriate that the given objects should be “clean” as well, else this suggests a mis-use of the method.

        • options

          optional sequence of loader options which will be applied to the Session.get() method when the merge operation loads the existing version of the object from the database.

          New in version 1.4.24.

    1. See also
    2. [make\_transient\_to\_detached()]($694f628462946390.md#sqlalchemy.orm.make_transient_to_detached "sqlalchemy.orm.make_transient_to_detached") - provides for an alternative means of “merging” a single object into the [Session]($694f628462946390.md#sqlalchemy.orm.Session "sqlalchemy.orm.Session")
    • attribute new

      The set of all instances marked as ‘new’ within this Session.

      Proxied for the Session class on behalf of the class.

    • attribute sqlalchemy.orm.scoping.scoped_session.no_autoflush

      Return a context manager that disables autoflush.

      Proxied for the class on behalf of the scoped_session class.

      e.g.:

      1. with session.no_autoflush:
      2. some_object = SomeClass()
      3. session.add(some_object)
      4. # won't autoflush
      5. some_object.related_thing = session.query(SomeRelated).first()

      Operations that proceed within the with: block will not be subject to flushes occurring upon query access. This is useful when initializing a series of objects which involve existing database queries, where the uncompleted object should not yet be flushed.

    • classmethod object_session(instance: object) → Optional[Session]

      Return the to which an object belongs.

      Proxied for the Session class on behalf of the class.

      This is an alias of object_session().

    • method query(*entities: _ColumnsClauseArgument[Any], **kwargs: Any) → Query[Any]

      Return a new object corresponding to this Session.

      Proxied for the class on behalf of the scoped_session class.

      Note that the object is legacy as of SQLAlchemy 2.0; the select() construct is now used to construct ORM queries.

      See also

      ORM Querying Guide

      - legacy API doc

    • method sqlalchemy.orm.scoping.scoped_session.query_property(query_cls: Optional[Type[[_T]]] = None) → _QueryDescriptorType

      return a class property which produces a Query object against the class and the current when called.

      e.g.:

      1. Session = scoped_session(sessionmaker())
      2. class MyClass:
      3. query = Session.query_property()
      4. # after mappers are defined
      5. result = MyClass.query.filter(MyClass.name=='foo').all()

      Produces instances of the session’s configured query class by default. To override and use a custom implementation, provide a query_cls callable. The callable will be invoked with the class’s mapper as a positional argument and a session keyword argument.

      There is no limit to the number of query properties placed on a class.

    • method sqlalchemy.orm.scoping.scoped_session.refresh(instance: object, attribute_names: Optional[Iterable[str]] = None, with_for_update: Optional[ForUpdateArg] = None) → None

      Expire and refresh attributes on the given instance.

      Proxied for the class on behalf of the scoped_session class.

      The selected attributes will first be expired as they would when using ; then a SELECT statement will be issued to the database to refresh column-oriented attributes with the current value available in the current transaction.

      relationship() oriented attributes will also be immediately loaded if they were already eagerly loaded on the object, using the same eager loading strategy that they were loaded with originally. Unloaded relationship attributes will remain unloaded, as will relationship attributes that were originally lazy loaded.

      New in version 1.4: - the method can also refresh eagerly loaded attributes.

      Tip

      While the Session.refresh() method is capable of refreshing both column and relationship oriented attributes, its primary focus is on refreshing of local column-oriented attributes on a single instance. For more open ended “refresh” functionality, including the ability to refresh the attributes on many objects at once while having explicit control over relationship loader strategies, use the feature instead.

      Note that a highly isolated transaction will return the same values as were previously read in that same transaction, regardless of changes in database state outside of that transaction. Refreshing attributes usually only makes sense at the start of a transaction where database rows have not yet been accessed.

      • Parameters:

        • attribute_names – optional. An iterable collection of string attribute names indicating a subset of attributes to be refreshed.

        • with_for_update – optional boolean True indicating FOR UPDATE should be used, or may be a dictionary containing flags to indicate a more specific set of FOR UPDATE flags for the SELECT; flags should match the parameters of Query.with_for_update(). Supersedes the parameter.

    1. See also
    2. [Refreshing / Expiring]($592600365cded3ff.md#session-expire) - introductory material
    3. [Session.expire()]($694f628462946390.md#sqlalchemy.orm.Session.expire "sqlalchemy.orm.Session.expire")
    4. [Session.expire\_all()]($694f628462946390.md#sqlalchemy.orm.Session.expire_all "sqlalchemy.orm.Session.expire_all")
    5. [Populate Existing]($661bd2ffd6937693.md#orm-queryguide-populate-existing) - allows any ORM query to refresh objects as they would be loaded normally.
    • method sqlalchemy.orm.scoping.scoped_session.remove() → None

      Dispose of the current , if present.

      This will first call Session.close() method on the current , which releases any existing transactional/connection resources still being held; transactions specifically are rolled back. The Session is then discarded. Upon next usage within the same scope, the will produce a new Session object.

    • method rollback() → None

      Rollback the current transaction in progress.

      Proxied for the Session class on behalf of the class.

      If no transaction is in progress, this method is a pass-through.

      The method always rolls back the topmost database transaction, discarding any nested transactions that may be in progress.

      See also

      Rolling Back

    • method sqlalchemy.orm.scoping.scoped_session.scalar(statement: , params: Optional[_CoreSingleExecuteParams] = None, *, execution_options: OrmExecuteOptionsParameter = {}, bind_arguments: Optional[_BindArguments] = None, **kw: Any) → Any

      Execute a statement and return a scalar result.

      Proxied for the Session class on behalf of the class.

      Usage and parameters are the same as that of Session.execute(); the return result is a scalar Python value.

    • method scalars(statement: Executable, params: Optional[_CoreAnyExecuteParams] = None, *, execution_options: OrmExecuteOptionsParameter = {}, bind_arguments: Optional[_BindArguments] = None, **kw: Any) → [Any]

      Execute a statement and return the results as scalars.

      Proxied for the Session class on behalf of the class.

      Usage and parameters are the same as that of Session.execute(); the return result is a filtering object which will return single elements rather than Row objects.

      • Returns:

        a object

      New in version 1.4.24.

      See also

      Selecting ORM Entities - contrasts the behavior of to Session.scalars()

    • attribute session_factory: sessionmaker[_S]

      The session_factory provided to __init__ is stored in this attribute and may be accessed at a later time. This can be useful when a new non-scoped is needed.

    class sqlalchemy.util.ScopedRegistry

    A Registry that can store one or multiple instances of a single class on the basis of a “scope” function.

    The object implements __call__ as the “getter”, so by calling myregistry() the contained object is returned for the current scope.

    • Parameters:

      • createfunc – a callable that returns a new object to be placed in the registry

      • scopefunc – a callable that will return a key to store/retrieve an object.

    Members

    __init__(), , has(),

    Class signature

    class sqlalchemy.util.ScopedRegistry (typing.Generic)

    • method __init__(createfunc: Callable[[], _T], scopefunc: Callable[[], Any])

      Construct a new ScopedRegistry.

      • Parameters:

        • createfunc – A creation function that will generate a new value for the current scope, if none is present.

        • scopefunc – A function that returns a hashable token representing the current scope (such as, current thread identifier).

    • method clear() → None

      Clear the current scope, if any.

    • method sqlalchemy.util.ScopedRegistry.set(obj: _T) → None

      Set the value for the current scope.

    class sqlalchemy.util.ThreadLocalRegistry

    A that uses a variable for storage.

    Class signature