Session API

Session and sessionmaker()

  • class sqlalchemy.orm.session.sessionmaker(bind=None, class=, _autoflush=True, autocommit=False, expire_on_commit=True, info=None, **kw)
  • Bases: sqlalchemy.orm.session._SessionClassMethods

A configurable Session factory.

The sessionmaker factory generates newSession objects when called, creating them giventhe configurational arguments established here.

e.g.:

  1. # global scope
  2. Session = sessionmaker(autoflush=False)
  3.  
  4. # later, in a local scope, create and use a session:
  5. sess = Session()

Any keyword arguments sent to the constructor itself will override the“configured” keywords:

  1. Session = sessionmaker()
  2.  
  3. # bind an individual session to a connection
  4. sess = Session(bind=connection)

The class also includes a method configure(), which canbe used to specify additional keyword arguments to the factory, whichwill take effect for subsequent Session objects generated.This is usually used to associate one or more Engine objectswith an existing sessionmaker factory before it is firstused:

  1. # application starts
  2. Session = sessionmaker()
  3.  
  4. # ... later
  5. engine = create_engine('sqlite:///foo.db')
  6. Session.configure(bind=engine)
  7.  
  8. sess = Session()
  • call(**local_kw)
  • Produce a new Session object using the configurationestablished in this sessionmaker.

In Python, the call method is invoked on an object whenit is “called” in the same way as a function:

  1. Session = sessionmaker()
  2. session = Session() # invokes sessionmaker.__call__()
  • eq()

inherited from the eq() method of object

Return self==value.

  • init(bind=None, class=, _autoflush=True, autocommit=False, expire_on_commit=True, info=None, **kw)
  • Construct a new sessionmaker.

All arguments here except for class correspond to argumentsaccepted by Session directly. See the[Session.init()](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.session.Session.__init_) docstring for more details on parameters.

  1. - Parameters
  2. -
  3. -

bind – a Engine or other Connectable withwhich newly created Session objects will be associated.

  1. -

class_ – class to use in order to create new Sessionobjects. Defaults to Session.

  1. -

autoflush – The autoflush setting to use with newly createdSession objects.

  1. -

autocommit – The autocommit setting to use with newly createdSession objects.

  1. -

expire_on_commit=True – the expire_on_commit setting to usewith newly created Session objects.

  1. -

info

optional dictionary of information that will be availablevia Session.info. Note this dictionary is updated, notreplaced, when the info parameter is specified to the specificSession construction operation.

New in version 0.9.0.

  1. -

**kw – all other keyword arguments are passed to theconstructor of newly created Session objects.

  • le()

inherited from the le() method of object

Return self<=value.

  • lt()

inherited from the lt() method of object

Return self

  • class sqlalchemy.orm.session.Session(bind=None, autoflush=True, expire_on_commit=True, _enable_transaction_accounting=True, autocommit=False, twophase=False, weak_identity_map=None, binds=None, extension=None, enable_baked_queries=True, info=None, query_cls=None)
  • Bases: sqlalchemy.orm.session._SessionClassMethods

Manages persistence operations for ORM-mapped objects.

The Session’s usage paradigm is described at Using the Session.

  • eq()

inherited from the eq() method of object

Return self==value.

See also the sessionmaker function which is used togenerate a Session-producing callable with a givenset of arguments.

  1. - Parameters
  2. -
  3. -

autocommit

Warning

The autocommit flag is not for general use, and if it isused, queries should only be invoked within the span of aSession.begin() / Session.commit() pair. Executingqueries outside of a demarcated transaction is a legacy modeof usage, and can in some cases lead to concurrent connectioncheckouts.

Defaults to False. When True, theSession does not keep a persistent transaction running,and will acquire connections from the engine on an as-needed basis,returning them immediately after their use. Flushes will begin andcommit (or possibly rollback) their own transaction if notransaction is present. When using this mode, theSession.begin() method is used to explicitly starttransactions.

See also

Autocommit Mode

  1. -

autoflush – When True, all query operations will issue aflush() call to this Session before proceeding.This is a convenience feature so that flush() neednot be called repeatedly in order for database queries to retrieveresults. It’s typical that autoflush is used in conjunctionwith autocommit=False. In this scenario, explicit calls toflush() are rarely needed; you usually only need tocall commit() (which flushes) to finalize changes.

  1. -

bind – An optional Engine or Connection towhich this Session should be bound. When specified, all SQLoperations performed by this session will execute via thisconnectable.

  1. -

binds

A dictionary which may specify any number ofEngine or Connection objects as the source ofconnectivity for SQL operations on a per-entity basis. The keysof the dictionary consist of any series of mapped classes,arbitrary Python classes that are bases for mapped classes,Table objects and Mapper objects. Thevalues of the dictionary are then instances of Engineor less commonly Connection objects. Operations whichproceed relative to a particular mapped class will consult thisdictionary for the closest matching entity in order to determinewhich Engine should be used for a particular SQLoperation. The complete heuristics for resolution aredescribed at Session.get_bind(). Usage looks like:

  1. Session = sessionmaker(binds={
  2. SomeMappedClass: create_engine('postgresql://engine1'),
  3. SomeDeclarativeBase: create_engine('postgresql://engine2'),
  4. some_mapper: create_engine('postgresql://engine3'),
  5. some_table: create_engine('postgresql://engine4'),
  6. })

See also

Partitioning Strategies (e.g. multiple database backends per Session)

Session.bind_mapper()

Session.bind_table()

Session.get_bind()

  1. -

class_ – Specify an alternate class other thansqlalchemy.orm.session.Session which should be used by thereturned class. This is the only argument that is local to thesessionmaker function, and is not sent directly to theconstructor for Session.

  1. -

enable_baked_queries

defaults to True. A flag consumedby the sqlalchemy.ext.baked extension to determine if“baked queries” should be cached, as is the normal operationof this extension. When set to False, all caching is disabled,including baked queries defined by the calling application aswell as those used internally. Setting this flag to Falsecan significantly reduce memory use, however will also degradeperformance for those areas that make use of baked queries(such as relationship loaders). Additionally, baked querylogic in the calling application or potentially within the ORMthat may be malfunctioning due to cache key collisions or similarcan be flagged by observing if this flag resolves the issue.

New in version 1.2.

  1. -

_enable_transaction_accounting

Alegacy-only flag which when False disables all 0.5-styleobject accounting on transaction boundaries.

Deprecated since version 0.7: The Session._enable_transaction_accounting parameter is deprecated and will be removed in a future release.

  1. -

expire_on_commit – Defaults to True. When True, allinstances will be fully expired after each commit(),so that all attribute/object access subsequent to a completedtransaction will load from the most recent database state.

  1. -

extension

An optionalSessionExtension instance, or a listof such instances, which will receive pre- and post- commit andflush events, as well as a post-rollback event.

Deprecated since version 0.7: SessionExtension is deprecated in favor of the SessionEvents listener interface. The Session.extension parameter will be removed in a future release.

  1. -

info

optional dictionary of arbitrary data to be associatedwith this Session. Is available via theSession.info attribute. Note the dictionary is copied atconstruction time so that modifications to the per-Session dictionary will be local to thatSession.

New in version 0.9.0.

  1. -

query_cls – Class which should be used to create new Queryobjects, as returned by the query() method.Defaults to Query.

  1. -

twophase – When True, all transactions will be started asa “two phase” transaction, i.e. using the “two phase” semanticsof the database in use along with an XID. During acommit(), after flush() has been issued for allattached databases, the prepare()method on each database’s TwoPhaseTransaction will becalled. This allows each database to roll back the entiretransaction, before each transaction is committed.

  1. -

weak_identity_map

Defaults to True - when set toFalse, objects placed in the Session will bestrongly referenced until explicitly removed or theSession is closed.

Deprecated since version 1.0: The Session.weak_identity_map parameter as well as the strong-referencing identity map are deprecated, and will be removed in a future release. For the use case where objects present in a Session need to be automatically strong referenced, see the recipe at Session Referencing Behavior for an event-based approach to maintaining strong identity references.

  • le()

inherited from the le() method of object

Return self<=value.

  • lt()

inherited from the lt() method of object

Return self

  • class sqlalchemy.orm.session.SessionTransaction(session, parent=None, nested=False)
  • A Session-level transaction.

SessionTransaction is a mostly behind-the-scenes objectnot normally referenced directly by application code. It coordinatesamong multiple Connection objects, maintaining a databasetransaction for each one individually, committing or rolling themback all at once. It also provides optional two-phase commit behaviorwhich can augment this coordination operation.

The Session.transaction attribute of Sessionrefers to the current SessionTransaction object in use, if any.The SessionTransaction.parent attribute refers to the parentSessionTransaction in the stack of SessionTransactionobjects. If this attribute is None, then this is the top of the stack.If non-None, then this SessionTransaction refers eitherto a so-called “subtransaction” or a “nested” transaction. A“subtransaction” is a scoping concept that demarcates an inner portionof the outermost “real” transaction. A nested transaction, whichis indicated when the SessionTransaction.nestedattribute is also True, indicates that this SessionTransactioncorresponds to a SAVEPOINT.

Life Cycle

A SessionTransaction is associated with a Sessionin its default mode of autocommit=False immediately, associatedwith no database connections. As the Session is called uponto emit SQL on behalf of various Engine or Connectionobjects, a corresponding Connection and associatedTransaction is added to a collection within theSessionTransaction object, becoming one of theconnection/transaction pairs maintained by theSessionTransaction. The start of a SessionTransactioncan be tracked using the SessionEvents.after_transaction_create()event.

The lifespan of the SessionTransaction ends when theSession.commit(), Session.rollback() orSession.close() methods are called. At this point, theSessionTransaction removes its association with its parentSession. A Session that is in autocommit=Falsemode will create a new SessionTransaction to replace itimmediately, whereas a Session that’s in autocommit=Truemode will remain without a SessionTransaction until theSession.begin() method is called. The end of aSessionTransaction can be tracked using theSessionEvents.after_transaction_end() event.

Nesting and Subtransactions

Another detail of SessionTransaction behavior is that it iscapable of “nesting”. This means that the Session.begin() methodcan be called while an existing SessionTransaction is alreadypresent, producing a new SessionTransaction that temporarilyreplaces the parent SessionTransaction. When aSessionTransaction is produced as nested, it assigns itself tothe Session.transaction attribute, and it additionally will assignthe previous SessionTransaction to its Session.parentattribute. The behavior is effectively astack, where Session.transaction refers to the current head ofthe stack, and the SessionTransaction.parent attribute allowstraversal up the stack until SessionTransaction.parent isNone, indicating the top of the stack.

When the scope of SessionTransaction is ended viaSession.commit() or Session.rollback(), it restores itsparent SessionTransaction back onto theSession.transaction attribute.

The purpose of this stack is to allow nesting ofSession.rollback() or Session.commit() calls in contextwith various flavors of Session.begin(). This nesting behaviorapplies to when Session.begin_nested() is used to emit aSAVEPOINT transaction, and is also used to produce a so-called“subtransaction” which allows a block of code to use abegin/rollback/commit sequence regardless of whether or not its enclosingcode block has begun a transaction. The flush() method, whethercalled explicitly or via autoflush, is the primary consumer of the“subtransaction” feature, in that it wishes to guarantee that it workswithin in a transaction block regardless of whether or not theSession is in transactional mode when the method is called.

Note that the flush process that occurs within the “autoflush” featureas well as when the Session.flush() method is used alwayscreates a SessionTransaction object. This object is normallya subtransaction, unless the Session is in autocommit modeand no transaction exists at all, in which case it’s the outermosttransaction. Any event-handling logic or other inspection logicneeds to take into account whether a SessionTransactionis the outermost transaction, a subtransaction, or a “nested” / SAVEPOINTtransaction.

See also

Session.rollback()

Session.commit()

Session.begin()

Session.begin_nested()

Session.is_active

SessionEvents.after_transaction_create()

SessionEvents.after_transaction_end()

SessionEvents.after_commit()

SessionEvents.after_rollback()

SessionEvents.after_soft_rollback()

  • nested = False
  • Indicates if this is a nested, or SAVEPOINT, transaction.

When SessionTransaction.nested is True, it is expectedthat SessionTransaction.parent will be True as well.

If this attribute is None, indicates thisSessionTransaction is at the top of the stack, andcorresponds to a real “COMMIT”/”ROLLBACK”block. If non-None, then this is either a “subtransaction”or a “nested” / SAVEPOINT transaction. If theSessionTransaction.nested attribute is True, thenthis is a SAVEPOINT, and if False, indicates this a subtransaction.

New in version 1.0.16: - use ._parent for previous versions

Session Utilities

  • sqlalchemy.orm.session.close_all_sessions()
  • Close all sessions in memory.

This function consults a global registry of all Session objectsand calls Session.close() on them, which resets them to a cleanstate.

This function is not for general use but may be useful for test suiteswithin the teardown scheme.

New in version 1.3.

  • sqlalchemy.orm.session.maketransient(_instance)
  • Alter the state of the given instance so that it is transient.

Note

make_transient() is a special-case function foradvanced use cases only.

The given mapped instance is assumed to be in the persistent ordetached state. The function will remove its association with anySession as well as its InstanceState.identity. Theeffect is that the object will behave as though it were newly constructed,except retaining any attribute / collection values that were loaded at thetime of the call. The InstanceState.deleted flag is also resetif this object had been deleted as a result of usingSession.delete().

Warning

make_transient() does not “unexpire” or otherwise eagerlyload ORM-mapped attributes that are not currently loaded at the timethe function is called. This includes attributes which:

  • were expired via Session.expire()

  • were expired as the natural effect of committing a sessiontransaction, e.g. Session.commit()

  • are normally lazy loaded but are not currently loaded

  • are “deferred” via Deferred Column Loading and are not yet loaded

  • were not present in the query which loaded this object, such as thatwhich is common in joined table inheritance and other scenarios.

After make_transient() is called, unloaded attributes suchas those above will normally resolve to the value None whenaccessed, or an empty collection for a collection-oriented attribute.As the object is transient and un-associated with any databaseidentity, it will no longer retrieve these values.

See also

make_transient_to_detached()

  • sqlalchemy.orm.session.maketransient_to_detached(_instance)
  • Make the given transient instance detached.

Note

make_transient_to_detached() is a special-case function foradvanced use cases only.

All attribute history on the given instancewill be reset as though the instance were freshly loadedfrom a query. Missing attributes will be marked as expired.The primary key attributes of the object, which are required, will be madeinto the “key” of the instance.

The object can then be added to a session, or mergedpossibly with the load=False flag, at which point it will lookas if it were loaded that way, without emitting SQL.

This is a special use case function that differs from a normalcall to Session.merge() in that a given persistent statecan be manufactured without any SQL calls.

New in version 0.9.5.

See also

make_transient()

Session.enable_relationship_loading()

  • sqlalchemy.orm.session.objectsession(_instance)
  • Return the Session to which the given instance belongs.

This is essentially the same as the InstanceState.sessionaccessor. See that attribute for details.

  • sqlalchemy.orm.util.wasdeleted(object)
  • Return True if the given object was deletedwithin a session flush.

This is regardless of whether or not the object ispersistent or detached.

See also

InstanceState.was_deleted

Attribute and State Management Utilities

These functions are provided by the SQLAlchemy attributeinstrumentation API to provide a detailed interface for dealingwith instances, attribute values, and history. Some of themare useful when constructing event listener functions, such asthose described in ORM Events.

  • sqlalchemy.orm.util.objectstate(_instance)
  • Given an object, return the InstanceStateassociated with the object.

Raises sqlalchemy.orm.exc.UnmappedInstanceErrorif no mapping is configured.

Equivalent functionality is available via the inspect()function as:

  1. inspect(instance)

Using the inspection system will raisesqlalchemy.exc.NoInspectionAvailable if the instance isnot part of a mapping.

  • sqlalchemy.orm.attributes.delattribute(_instance, key)
  • Delete the value of an attribute, firing history events.

This function may be used regardless of instrumentationapplied directly to the class, i.e. no descriptors are required.Custom attribute management schemes will need to make usageof this method to establish attribute state as understoodby SQLAlchemy.

  • sqlalchemy.orm.attributes.getattribute(_instance, key)
  • Get the value of an attribute, firing any callables required.

This function may be used regardless of instrumentationapplied directly to the class, i.e. no descriptors are required.Custom attribute management schemes will need to make usageof this method to make usage of attribute state as understoodby SQLAlchemy.

  • sqlalchemy.orm.attributes.gethistory(_obj, key, passive=symbol('PASSIVE_OFF'))
  • Return a History record for the given objectand attribute key.

This is the pre-flush history for a given attribute, which isreset each time the Session flushes changes to thecurrent database transaction.

Note

Prefer to use the AttributeState.history andAttributeState.load_history() accessors to retrieve theHistory for instance attributes.

  • Parameters
    • obj – an object whose class is instrumented by theattributes package.

    • key – string attribute name.

    • passive – indicates loading behavior for the attributeif the value is not already present. This is abitflag attribute, which defaults to the symbolPASSIVE_OFF indicating all necessary SQLshould be emitted.

See also

AttributeState.history

AttributeState.load_history() - retrieve historyusing loader callables if the value is not locally present.

  • sqlalchemy.orm.attributes.initcollection(_obj, key)
  • Initialize a collection attribute and return the collection adapter.

This function is used to provide direct access to collection internalsfor a previously unloaded attribute. e.g.:

  1. collection_adapter = init_collection(someobject, 'elements')
  2. for elem in values:
  3. collection_adapter.append_without_event(elem)

For an easier way to do the above, seeset_committed_value().

  • Parameters
    • obj – a mapped object

    • key – string attribute name where the collection is located.

  • sqlalchemy.orm.attributes.flagmodified(_instance, key)
  • Mark an attribute on an instance as ‘modified’.

This sets the ‘modified’ flag on the instance andestablishes an unconditional change event for the given attribute.The attribute must have a value present, else anInvalidRequestError is raised.

To mark an object “dirty” without referring to any specific attributeso that it is considered within a flush, use theattributes.flag_dirty() call.

See also

attributes.flag_dirty()

  • sqlalchemy.orm.attributes.flagdirty(_instance)
  • Mark an instance as ‘dirty’ without any specific attribute mentioned.

This is a special operation that will allow the object to travel throughthe flush process for interception by events such asSessionEvents.before_flush(). Note that no SQL will be emitted inthe flush process for an object that has no changes, even if marked dirtyvia this method. However, a SessionEvents.before_flush() handlerwill be able to see the object in the Session.dirty collection andmay establish changes on it, which will then be included in the SQLemitted.

New in version 1.2.

See also

attributes.flag_modified()

  • sqlalchemy.orm.attributes.instance_state()
  • Return the InstanceState for a givenmapped object.

This function is the internal versionof object_state(). Theobject_state() and/or theinspect() function is preferred hereas they each emit an informative exceptionif the given object is not mapped.

  • sqlalchemy.orm.instrumentation.isinstrumented(_instance, key)
  • Return True if the given attribute on the given instance isinstrumented by the attributes package.

This function may be used regardless of instrumentationapplied directly to the class, i.e. no descriptors are required.

  • sqlalchemy.orm.attributes.setattribute(_instance, key, value, initiator=None)
  • Set the value of an attribute, firing history events.

This function may be used regardless of instrumentationapplied directly to the class, i.e. no descriptors are required.Custom attribute management schemes will need to make usageof this method to establish attribute state as understoodby SQLAlchemy.

  • Parameters
    • instance – the object that will be modified

    • key – string name of the attribute

    • value – value to assign

    • initiator

an instance of Event that would havebeen propagated from a previous event listener. This argumentis used when the set_attribute() function is being used withinan existing event listening function where an Event objectis being supplied; the object may be used to track the origin of thechain of events.

New in version 1.2.3.

  • sqlalchemy.orm.attributes.setcommitted_value(_instance, key, value)
  • Set the value of an attribute with no history events.

Cancels any previous history present. The value should bea scalar value for scalar-holding attributes, oran iterable for any collection-holding attribute.

This is the same underlying method used when a lazy loaderfires off and loads additional data from the database.In particular, this method can be used by application codewhich has loaded additional attributes or collections throughseparate queries, which can then be attached to an instanceas though it were part of its original loaded state.

A 3-tuple of added, unchanged and deleted values,representing the changes which have occurred on an instrumentedattribute.

The easiest way to get a History object for a particularattribute on an object is to use the inspect() function:

  1. from sqlalchemy import inspect
  2.  
  3. hist = inspect(myobject).attrs.myattribute.history

Each tuple member is an iterable sequence:

  • added - the collection of items added to the attribute (the firsttuple element).

  • unchanged - the collection of items that have not changed on theattribute (the second tuple element).

  • deleted - the collection of items that have been removed from theattribute (the third tuple element).

  • empty()

  • Return True if this History has no changesand no existing, unchanged state.

  • has_changes()

  • Return True if this History has changes.

  • non_added()

  • Return a collection of unchanged + deleted.

  • non_deleted()

  • Return a collection of added + unchanged.

  • sum()

  • Return a collection of added + unchanged + deleted.