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.:
- # global scope
- Session = sessionmaker(autoflush=False)
- # later, in a local scope, create and use a session:
- sess = Session()
Any keyword arguments sent to the constructor itself will override the“configured” keywords:
- Session = sessionmaker()
- # bind an individual session to a connection
- 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:
- # application starts
- Session = sessionmaker()
- # ... later
- engine = create_engine('sqlite:///foo.db')
- Session.configure(bind=engine)
- sess = Session()
call
(**local_kw)- Produce a new
Session
object using the configurationestablished in thissessionmaker
.
In Python, the call
method is invoked on an object whenit is “called” in the same way as a function:
- Session = sessionmaker()
- session = Session() # invokes sessionmaker.__call__()
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.
- Parameters
-
-
bind – a Engine
or other Connectable
withwhich newly created Session
objects will be associated.
-
class_ – class to use in order to create new Session
objects. Defaults to Session
.
-
autoflush – The autoflush setting to use with newly createdSession
objects.
-
autocommit – The autocommit setting to use with newly createdSession
objects.
-
expire_on_commit=True – the expire_on_commit setting to usewith newly created Session
objects.
-
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.
-
**kw – all other keyword arguments are passed to theconstructor of newly created Session
objects.
inherited from the le()
method of object
Return self<=value.
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.
inherited from the eq()
method of object
Return self==value.
init
(bind=None, autoflush=True, expire_on_commit=True, enabletransaction_accounting=True, autocommit=False, twophase=False, weak_identity_map=None, binds=None, extension=None, enable_baked_queries=True, info=None, query_cls=None)[](https://docs.sqlalchemy.org/en/13/orm/#sqlalchemy.orm.session.Session.init__)- Construct a new Session.
See also the sessionmaker
function which is used togenerate a Session
-producing callable with a givenset of arguments.
- Parameters
-
-
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
-
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.
-
bind – An optional Engine
or Connection
towhich this Session
should be bound. When specified, all SQLoperations performed by this session will execute via thisconnectable.
-
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 Engine
or 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:
- Session = sessionmaker(binds={
- SomeMappedClass: create_engine('postgresql://engine1'),
- SomeDeclarativeBase: create_engine('postgresql://engine2'),
- some_mapper: create_engine('postgresql://engine3'),
- some_table: create_engine('postgresql://engine4'),
- })
See also
Partitioning Strategies (e.g. multiple database backends per Session)
-
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
.
-
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 False
can 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.
-
_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.
-
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.
-
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.
-
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.
-
query_cls – Class which should be used to create new Queryobjects, as returned by the query()
method.Defaults to Query
.
-
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.
-
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.
inherited from the le()
method of object
Return self<=value.
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 Session
refers to the current SessionTransaction
object in use, if any.The SessionTransaction.parent
attribute refers to the parentSessionTransaction
in the stack of SessionTransaction
objects. 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.nested
attribute is also True, indicates that this SessionTransaction
corresponds to a SAVEPOINT.
Life Cycle
A SessionTransaction
is associated with a Session
in 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 Connection
objects, 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 SessionTransaction
can 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=False
mode will create a new SessionTransaction
to replace itimmediately, whereas a Session
that’s in autocommit=True
mode 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.parent
attribute. 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 SessionTransaction
is the outermost transaction, a subtransaction, or a “nested” / SAVEPOINTtransaction.
See also
Session.is_active
SessionEvents.after_transaction_create()
SessionEvents.after_transaction_end()
SessionEvents.after_rollback()
SessionEvents.after_soft_rollback()
When SessionTransaction.nested
is True, it is expectedthat SessionTransaction.parent
will be True as well.
- property
parent
- The parent
SessionTransaction
of thisSessionTransaction
.
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
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
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
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.session
accessor. 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
InstanceState
associated with the object.
Raises sqlalchemy.orm.exc.UnmappedInstanceError
if no mapping is configured.
Equivalent functionality is available via the inspect()
function as:
- 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
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.:
- collection_adapter = init_collection(someobject, 'elements')
- for elem in values:
- collection_adapter.append_without_event(elem)
For an easier way to do the above, seeset_committed_value()
.
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
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
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
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.
- class
sqlalchemy.orm.attributes.
History
- Bases:
sqlalchemy.orm.attributes.History
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:
- from sqlalchemy import inspect
- 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).Return True if this
History
has no changesand no existing, unchanged state.Return True if this
History
has changes.Return a collection of unchanged + deleted.
Return a collection of added + unchanged.
- Return a collection of added + unchanged + deleted.