Session API — SQLAlchemy 1.3 Documentation (original) (raw)

Session and sessionmaker()

Object Name Description
Session Manages persistence operations for ORM-mapped objects.
sessionmaker A configurable Session factory.
SessionTransaction A Session-level transaction.

class sqlalchemy.orm.session.sessionmaker(bind=None, class_=<class 'sqlalchemy.orm.session.Session'>, autoflush=True, autocommit=False, expire_on_commit=True, info=None, **kw)

A configurable Session factory.

The sessionmaker factory generates newSession objects when called, creating them given the 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 can be used to specify additional keyword arguments to the factory, which will take effect for subsequent Session objects generated. This is usually used to associate one or more Engineobjects with an existing sessionmaker factory before it is first used:

application starts

Session = sessionmaker()

... later

engine = create_engine('sqlite:///foo.db') Session.configure(bind=engine)

sess = Session()

Class signature

class sqlalchemy.orm.session.sessionmaker (sqlalchemy.orm.session._SessionClassMethods)

method sqlalchemy.orm.session.sessionmaker.__call__(**local_kw)

Produce a new Session object using the configuration established in this sessionmaker.

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

Session = sessionmaker() session = Session() # invokes sessionmaker.call()

method sqlalchemy.orm.session.sessionmaker.__init__(bind=None, class_=<class 'sqlalchemy.orm.session.Session'>, autoflush=True, autocommit=False, expire_on_commit=True, info=None, **kw)

Construct a new sessionmaker.

All arguments here except for class_ correspond to arguments accepted by Session directly. See theSession.__init__() docstring for more details on parameters.

Parameters:

classmethod sqlalchemy.orm.session.sessionmaker.close_all()

inherited from the sqlalchemy.orm.session._SessionClassMethods.close_all method of sqlalchemy.orm.session._SessionClassMethods

Close all sessions in memory.

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 sqlalchemy.orm.session.sessionmaker.configure(**new_kw)

(Re)configure the arguments for this sessionmaker.

e.g.:

Session = sessionmaker()

Session.configure(bind=create_engine('sqlite://'))

classmethod sqlalchemy.orm.session.sessionmaker.identity_key(orm_util, *args, **kwargs)

inherited from the sqlalchemy.orm.session._SessionClassMethods.identity_key method of sqlalchemy.orm.session._SessionClassMethods

Return an identity key.

This is an alias of identity_key().

classmethod sqlalchemy.orm.session.sessionmaker.object_session(instance)

inherited from the sqlalchemy.orm.session._SessionClassMethods.object_session method of sqlalchemy.orm.session._SessionClassMethods

Return the Session to which an object belongs.

This is an alias of object_session().

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)

Manages persistence operations for ORM-mapped objects.

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

Members

__init__(), add(), add_all(), begin(), begin_nested(), bind_mapper(), bind_table(), bulk_insert_mappings(), bulk_save_objects(), bulk_update_mappings(), close(), close_all(), commit(), connection(), delete(), deleted, dirty, enable_relationship_loading(), execute(), expire(), expire_all(), expunge(), expunge_all(), flush(), get_bind(), identity_key(), identity_map, info, invalidate(), is_active, is_modified(), merge(), new, no_autoflush, object_session(), prepare(), prune(), query(), refresh(), rollback(), scalar(), transaction

Class signature

class sqlalchemy.orm.session.Session (sqlalchemy.orm.session._SessionClassMethods)

method sqlalchemy.orm.session.Session.__init__(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)

Construct a new Session.

See also the sessionmaker function which is used to generate a Session-producing callable with a given set of arguments.

Parameters:

method sqlalchemy.orm.session.Session.add(instance, _warn=True)

Place an object in the Session.

Its state will be persisted to the database on the next flush operation.

Repeated calls to add() will be ignored. The opposite of add()is expunge().

method sqlalchemy.orm.session.Session.add_all(instances)

Add the given collection of instances to this Session.

method sqlalchemy.orm.session.Session.begin(subtransactions=False, nested=False)

Begin a transaction on this Session.

Warning

The Session.begin() method is part of a larger pattern of use with the Session known as autocommit mode. This is essentially a legacy mode of use and is not necessary for new applications. The Sessionnormally handles the work of “begin” transparently, which in turn relies upon the Python DBAPI to transparently “begin” transactions; there is no need to explicitly begin transactionswhen using modern Session programming patterns. In its default mode of autocommit=False, theSession does all of its work within the context of a transaction, so as soon as you callSession.commit(), the next transaction is implicitly started when the next database operation is invoked. SeeAutocommit Mode for further background.

The method will raise an error if this Session is already inside of a transaction, unlessSession.begin.subtransactions orSession.begin.nested are specified. A “subtransaction” is essentially a code embedding pattern that does not affect the transactional state of the database connection unless a rollback is emitted, in which case the whole transaction is rolled back. For documentation on subtransactions, please seeUsing Subtransactions with Autocommit.

Parameters:

Returns:

the SessionTransaction object. Note thatSessionTransactionacts as a Python context manager, allowing Session.begin()to be used in a “with” block. See Autocommit Mode for an example.

method sqlalchemy.orm.session.Session.begin_nested()

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

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.

Returns:

the SessionTransaction object. Note thatSessionTransaction acts as a context manager, allowingSession.begin_nested() to be used in a “with” block. See Using SAVEPOINT for a usage example.

method sqlalchemy.orm.session.Session.bind_mapper(mapper, bind)

Associate a Mapper or arbitrary Python class with a “bind”, e.g. an Engine orConnection.

The given entity is added to a lookup used by theSession.get_bind() method.

Parameters:

method sqlalchemy.orm.session.Session.bind_table(table, bind)

Associate a Table with a “bind”, e.g. anEngineor Connection.

The given Table is added to a lookup used by theSession.get_bind() method.

Parameters:

method sqlalchemy.orm.session.Session.bulk_insert_mappings(mapper, mappings, return_defaults=False, render_nulls=False)

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

The bulk insert feature allows plain Python dictionaries to be used as the source of simple INSERT operations which can be more easily grouped together into higher performing “executemany” operations. Using dictionaries, there is no “history” or session state management features in use, reducing latency when inserting large numbers of simple rows.

The values within the dictionaries as given are typically passed without modification into Core sqlalchemy.sql.expression.Insert() constructs, after organizing the values within them across the tables to which the given mapper is mapped.

New in version 1.0.0.

Warning

The bulk insert feature allows for a lower-latency INSERT of rows at the expense of most other unit-of-work features. Features such as object management, relationship handling, and SQL clause support are silently omitted in favor of raw INSERT of records.

Please read the list of caveats at ORM Compatibility / Caveats before using this method, and fully test and confirm the functionality of all code developed using these systems.

Parameters:

method sqlalchemy.orm.session.Session.bulk_save_objects(objects, return_defaults=False, update_changed_only=True, preserve_order=True)

Perform a bulk save of the given list of objects.

The bulk save feature allows mapped objects to be used as the source of simple INSERT and UPDATE operations which can be more easily grouped together into higher performing “executemany” operations; the extraction of data from the objects is also performed using a lower-latency process that ignores whether or not attributes have actually been modified in the case of UPDATEs, and also ignores SQL expressions.

The objects as given are not added to the session and no additional state is established on them, unless the return_defaults flag is also set, in which case primary key attributes and server-side default values will be populated.

New in version 1.0.0.

Warning

The bulk save feature allows for a lower-latency INSERT/UPDATE of rows at the expense of most other unit-of-work features. Features such as object management, relationship handling, and SQL clause support are silently omitted in favor of raw INSERT/UPDATES of records.

Please read the list of caveats at ORM Compatibility / Caveats before using this method, and fully test and confirm the functionality of all code developed using these systems.

Parameters:

method sqlalchemy.orm.session.Session.bulk_update_mappings(mapper, mappings)

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

The bulk update feature allows plain Python dictionaries to be used as the source of simple UPDATE operations which can be more easily grouped together into higher performing “executemany” operations. Using dictionaries, there is no “history” or session state management features in use, reducing latency when updating large numbers of simple rows.

New in version 1.0.0.

Warning

The bulk update feature allows for a lower-latency UPDATE of rows at the expense of most other unit-of-work features. Features such as object management, relationship handling, and SQL clause support are silently omitted in favor of raw UPDATES of records.

Please read the list of caveats at ORM Compatibility / Caveats before using this method, and fully test and confirm the functionality of all code developed using these systems.

Parameters:

method sqlalchemy.orm.session.Session.close()

Close this Session.

This clears all items and ends any transaction in progress.

If this session were created with autocommit=False, a new transaction is immediately begun. Note that this new transaction does not use any connection resources until they are first needed.

classmethod sqlalchemy.orm.session.Session.close_all()

inherited from the sqlalchemy.orm.session._SessionClassMethods.close_all method of sqlalchemy.orm.session._SessionClassMethods

Close all sessions in memory.

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 sqlalchemy.orm.session.Session.commit()

Flush pending changes and commit the current transaction.

If no transaction is in progress, this method raises anInvalidRequestError.

By default, the Session also expires all database loaded state on all ORM-managed attributes after transaction commit. This so that subsequent operations load the most recent data from the database. This behavior can be disabled using the expire_on_commit=False option to sessionmaker or the Session constructor.

If a subtransaction is in effect (which occurs when begin() is called multiple times), the subtransaction will be closed, and the next call to commit() will operate on the enclosing transaction.

When using the Session in its default mode ofautocommit=False, a new transaction will be begun immediately after the commit, but note that the newly begun transaction does not use any connection resources until the first SQL is actually emitted.

method sqlalchemy.orm.session.Session.connection(mapper=None, clause=None, bind=None, close_with_result=False, execution_options=None, **kw)

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

If this Session is configured with autocommit=False, either the Connection corresponding to the current transaction is returned, or if no transaction is in progress, a new one is begun and the Connectionreturned (note that no transactional state is established with the DBAPI until the first SQL statement is emitted).

Alternatively, if this Session is configured withautocommit=True, an ad-hoc Connection is returned using Engine.connect() on the underlyingEngine.

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

Parameters:

method sqlalchemy.orm.session.Session.delete(instance)

Mark an instance as deleted.

The database delete operation occurs upon flush().

attribute sqlalchemy.orm.session.Session.deleted

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

attribute sqlalchemy.orm.session.Session.dirty

The set of all persistent instances considered dirty.

E.g.:

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 sqlalchemy.orm.session.Session.enable_relationship_loading(obj)

Associate an object with this Session for related object loading.

Warning

enable_relationship_loading() exists to serve special use cases and is not recommended for general use.

Accesses of attributes mapped with relationship()will attempt to load a value from the database using thisSession as the source of connectivity. The values will be loaded based on foreign key and primary key values present on this object - if not present, then those relationships will be unavailable.

The object will be attached to this session, but willnot participate in any persistence operations; its state for almost all purposes will remain either “transient” or “detached”, except for the case of relationship loading.

Also note that backrefs will often not work as expected. Altering a relationship-bound attribute on the target object may not fire off a backref event, if the effective value is what was already loaded from a foreign-key-holding value.

The Session.enable_relationship_loading() method is similar to the load_on_pending flag on relationship(). Unlike that flag, Session.enable_relationship_loading() allows an object to remain transient while still being able to load related items.

To make a transient object associated with a Sessionvia Session.enable_relationship_loading() pending, add it to the Session using Session.add() normally. If the object instead represents an existing identity in the database, it should be merged using Session.merge().

Session.enable_relationship_loading() does not improve behavior when the ORM is used normally - object references should be constructed at the object level, not at the foreign key level, so that they are present in an ordinary way before flush() proceeds. This method is not intended for general use.

See also

relationship.load_on_pending - this flag allows per-relationship loading of many-to-ones on items that are pending.

make_transient_to_detached() - allows for an object to be added to a Session without SQL emitted, which then will unexpire attributes on access.

method sqlalchemy.orm.session.Session.execute(clause, params=None, mapper=None, bind=None, **kw)

Execute a SQL expression construct or string statement within the current transaction.

Returns a ResultProxy representing results of the statement execution, in the same manner as that of anEngine orConnection.

E.g.:

result = session.execute( user_table.select().where(user_table.c.id == 5) )

Session.execute() accepts any executable clause construct, such as select(),insert(),update(),delete(), andtext(). Plain SQL strings can be passed as well, which in the case of Session.execute() only will be interpreted the same as if it were passed via atext() construct. That is, the following usage:

result = session.execute( "SELECT * FROM user WHERE id=:param", {"param":5} )

is equivalent to:

from sqlalchemy import text result = session.execute( text("SELECT * FROM user WHERE id=:param"), {"param":5} )

The second positional argument to Session.execute() is an optional parameter set. Similar to that ofConnection.execute(), whether this is passed as a single dictionary, or a sequence of dictionaries, determines whether the DBAPI cursor’s execute() or executemany() is used to execute the statement. An INSERT construct may be invoked for a single row:

result = session.execute( users.insert(), {"id": 7, "name": "somename"})

or for multiple rows:

result = session.execute(users.insert(), [ {"id": 7, "name": "somename7"}, {"id": 8, "name": "somename8"}, {"id": 9, "name": "somename9"} ])

The statement is executed within the current transactional context of this Session. The Connectionwhich is used to execute the statement can also be acquired directly by calling the Session.connection() method. Both methods use a rule-based resolution scheme in order to determine theConnection, which in the average case is derived directly from the “bind” of the Session itself, and in other cases can be based on the mapper()and Table objects passed to the method; see the documentation for Session.get_bind() for a full description of this scheme.

The Session.execute() method does not invoke autoflush.

The ResultProxy returned by theSession.execute()method is returned with the “close_with_result” flag set to true; the significance of this flag is that if this Session is autocommitting and does not have a transaction-dedicatedConnection available, a temporaryConnection is established for the statement execution, which is closed (meaning, returned to the connection pool) when the ResultProxyhas consumed all available data. This applies only when theSession is configured with autocommit=True and no transaction has been started.

Parameters:

method sqlalchemy.orm.session.Session.expire(instance, attribute_names=None)

Expire the attributes on an instance.

Marks the attributes of an instance as out of date. When an expired attribute is next accessed, a query will be issued to theSession 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 Session 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:

method sqlalchemy.orm.session.Session.expire_all()

Expires all persistent instances within this Session.

When any attributes on a persistent instance is next accessed, a query will be issued using theSession 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 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_all() should not be needed when autocommit is False, assuming the transaction is isolated.

method sqlalchemy.orm.session.Session.expunge(instance)

Remove the instance from this Session.

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

method sqlalchemy.orm.session.Session.expunge_all()

Remove all object instances from this Session.

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

method sqlalchemy.orm.session.Session.flush(objects=None)

Flush all the object changes to the database.

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.

For autocommit Sessions with no active manual transaction, flush() will create a transaction on the fly that surrounds the entire set of operations into the flush.

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 sqlalchemy.orm.session.Session.get_bind(mapper=None, clause=None)

Return a “bind” to which this Session is bound.

The “bind” is usually an instance of Engine, except in the case where the Session has been explicitly bound directly to a Connection.

For a multiply-bound or unbound Session, themapper or clause arguments are used to determine the appropriate bind to return.

Note that the “mapper” argument is usually present when Session.get_bind() is called via an ORM operation such as a Session.query(), each individual INSERT/UPDATE/DELETE operation within aSession.flush(), call, etc.

The order of resolution is:

  1. if mapper given and Session.binds is present, locate a bind based first on the mapper in use, then on the mapped class in use, then on any base classes that are present in the __mro__ of the mapped class, from more specific superclasses to more general.
  2. if clause given and Session.binds is present, locate a bind based on Table objects found in the given clause present in Session.binds.
  3. if Session.binds is present, return that.
  4. if clause given, attempt to return a bind linked to the MetaData ultimately associated with the clause.
  5. if mapper given, attempt to return a bind linked to the MetaData ultimately associated with the Table or other selectable to which the mapper is mapped.
  6. No bind can be found, UnboundExecutionErroris raised.

Note that the Session.get_bind() method can be overridden on a user-defined subclass of Session to provide any kind of bind resolution scheme. See the example atCustom Vertical Partitioning.

Parameters:

classmethod sqlalchemy.orm.session.Session.identity_key(orm_util, *args, **kwargs)

inherited from the sqlalchemy.orm.session._SessionClassMethods.identity_key method of sqlalchemy.orm.session._SessionClassMethods

Return an identity key.

This is an alias of identity_key().

attribute sqlalchemy.orm.session.Session.identity_map = None

A mapping of object identities to objects themselves.

Iterating through Session.identity_map.values() provides access to the full set of persistent objects (i.e., those that have row identity) currently in the session.

See also

identity_key() - helper function to produce the keys used in this dictionary.

attribute sqlalchemy.orm.session.Session.info

A user-modifiable dictionary.

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

New in version 0.9.0.

method sqlalchemy.orm.session.Session.invalidate()

Close this Session, using connection invalidation.

This is a variant of Session.close() that will additionally ensure that the Connection.invalidate()method will be called on all Connection objects. This can be called when the database is known to be in a state where the connections are no longer safe to be used.

E.g.:

try: sess = Session() sess.add(User()) sess.commit() except gevent.Timeout: sess.invalidate() raise except: sess.rollback() raise

This clears all items and ends any transaction in progress.

If this session were created with autocommit=False, a new transaction is immediately begun. Note that this new transaction does not use any connection resources until they are first needed.

New in version 0.9.9.

attribute sqlalchemy.orm.session.Session.is_active

True if this Session is in “transaction mode” and is not in “partial rollback” state.

The Session in its default mode of autocommit=Falseis essentially always in “transaction mode”, in that aSessionTransaction is associated with it as soon as it is instantiated. This SessionTransaction is immediately replaced with a new one as soon as it is ended, due to a rollback, commit, or close operation.

“Transaction mode” does not indicate whether or not actual database connection resources are in use; theSessionTransaction object coordinates among zero or more actual database transactions, and starts out with none, accumulating individual DBAPI connections as different data sources are used within its scope. The best way to track when a particularSession has actually begun to use DBAPI resources is to implement a listener using the SessionEvents.after_begin()method, which will deliver both the Session as well as the target Connection to a user-defined event listener.

The “partial rollback” state refers to when an “inner” transaction, typically used during a flush, encounters an error and emits a rollback of the DBAPI connection. At this point, theSession is in “partial rollback” and awaits for the user to call Session.rollback(), in order to close out the transaction stack. It is in this “partial rollback” period that theis_active flag returns False. After the call toSession.rollback(), the SessionTransaction is replaced with a new one and is_active returns True again.

When a Session is used in autocommit=True mode, theSessionTransaction is only instantiated within the scope of a flush call, or when Session.begin() is called. Sois_active will always be False outside of a flush orSession.begin() block in this mode, and will be Truewithin the Session.begin() block as long as it doesn’t enter “partial rollback” state.

From all the above, it follows that the only purpose to this flag is for application frameworks that wish to detect if a “rollback” is necessary within a generic error handling routine, forSession objects that would otherwise be in “partial rollback” mode. In a typical integration case, this is also not necessary as it is standard practice to emitSession.rollback() unconditionally within the outermost exception catch.

To track the transactional state of a Session fully, use event listeners, primarily the SessionEvents.after_begin(),SessionEvents.after_commit(),SessionEvents.after_rollback() and related events.

method sqlalchemy.orm.session.Session.is_modified(instance, include_collections=True, passive=None)

Return True if the given instance has locally modified attributes.

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 theSession.dirty collection; a full test for each attribute’s net “dirty” status is performed.

E.g.:

return session.is_modified(someobject)

A few caveats to this method apply:

Parameters:

method sqlalchemy.orm.session.Session.merge(instance, load=True)

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

Session.merge() 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 Merging for a detailed discussion of merging.

Parameters:

See also

make_transient_to_detached() - provides for an alternative means of “merging” a single object into the Session

attribute sqlalchemy.orm.session.Session.new

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

attribute sqlalchemy.orm.session.Session.no_autoflush

Return a context manager that disables autoflush.

e.g.:

with session.no_autoflush:

some_object = SomeClass()
session.add(some_object)
# won't autoflush
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 sqlalchemy.orm.session.Session.object_session(instance)

inherited from the sqlalchemy.orm.session._SessionClassMethods.object_session method of sqlalchemy.orm.session._SessionClassMethods

Return the Session to which an object belongs.

This is an alias of object_session().

method sqlalchemy.orm.session.Session.prepare()

Prepare the current transaction in progress for two phase commit.

If no transaction is in progress, this method raises anInvalidRequestError.

Only root transactions of two phase sessions can be prepared. If the current transaction is not such, anInvalidRequestError is raised.

method sqlalchemy.orm.session.Session.prune()

Remove unreferenced instances cached in the identity map.

Deprecated since version 0.7: The Session.prune() method is deprecated along with Session.weak_identity_map. This method will be removed in a future release.

Note that this method is only meaningful if “weak_identity_map” is set to False. The default weak identity map is self-pruning.

Removes any object in this Session’s identity map that is not referenced in user code, modified, new or scheduled for deletion. Returns the number of objects pruned.

method sqlalchemy.orm.session.Session.query(*entities, **kwargs)

Return a new Query object corresponding to thisSession.

method sqlalchemy.orm.session.Session.refresh(instance, attribute_names=None, with_for_update=None, lockmode=None)

Expire and refresh the attributes on the given instance.

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

Lazy-loaded relational attributes will remain lazily loaded, so that the instance-wide refresh operation will be followed immediately by the lazy load of that attribute.

Eagerly-loaded relational attributes will eagerly load within the single refresh operation.

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 - usage ofSession.refresh() usually only makes sense if non-ORM SQL statement were emitted in the ongoing transaction, or if autocommit mode is turned on.

Parameters:

method sqlalchemy.orm.session.Session.rollback()

Rollback the current transaction in progress.

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

This method rolls back the current transaction or nested transaction regardless of subtransactions being in effect. All subtransactions up to the first real transaction are closed. Subtransactions occur whenbegin() is called multiple times.

method sqlalchemy.orm.session.Session.scalar(clause, params=None, mapper=None, bind=None, **kw)

Like Session.execute() but return a scalar result.

attribute sqlalchemy.orm.session.Session.transaction = None

The current active or inactive SessionTransaction.

class sqlalchemy.orm.session.SessionTransaction(session, parent=None, nested=False)

A Session-level transaction.

SessionTransaction is a mostly behind-the-scenes object not normally referenced directly by application code. It coordinates among multiple Connection objects, maintaining a database transaction for each one individually, committing or rolling them back all at once. It also provides optional two-phase commit behavior which 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 either to a so-called “subtransaction” or a “nested” transaction. A “subtransaction” is a scoping concept that demarcates an inner portion of the outermost “real” transaction. A nested transaction, which is indicated when the SessionTransaction.nestedattribute is also True, indicates that this SessionTransactioncorresponds to a SAVEPOINT.

Life Cycle

A SessionTransaction is associated with a Session in its default mode of autocommit=False immediately, associated with no database connections. As the Session is called upon to emit SQL on behalf of various Engine orConnectionobjects, a corresponding Connection and associatedTransaction is added to a collection within theSessionTransaction object, becoming one of the connection/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 it immediately, 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 is capable of “nesting”. This means that the Session.begin() method can be called while an existing SessionTransaction is already present, producing a new SessionTransaction that temporarily replaces the parent SessionTransaction. When aSessionTransaction is produced as nested, it assigns itself to the Session.transaction attribute, and it additionally will assign the previous SessionTransaction to its Session.parentattribute. The behavior is effectively a stack, where Session.transaction refers to the current head of the stack, and the SessionTransaction.parent attribute allows traversal 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 its parent SessionTransaction back onto theSession.transaction attribute.

The purpose of this stack is to allow nesting ofSession.rollback() or Session.commit() calls in context with various flavors of Session.begin(). This nesting behavior applies to when Session.begin_nested() is used to emit a SAVEPOINT transaction, and is also used to produce a so-called “subtransaction” which allows a block of code to use a begin/rollback/commit sequence regardless of whether or not its enclosing code block has begun a transaction. The flush() method, whether called explicitly or via autoflush, is the primary consumer of the “subtransaction” feature, in that it wishes to guarantee that it works within 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” feature as well as when the Session.flush() method is used alwayscreates a SessionTransaction object. This object is normally a subtransaction, unless the Session is in autocommit mode and no transaction exists at all, in which case it’s the outermost transaction. Any event-handling logic or other inspection logic needs to take into account whether a SessionTransactionis the outermost transaction, a subtransaction, or a “nested” / SAVEPOINT transaction.

attribute sqlalchemy.orm.session.SessionTransaction.nested = False

Indicates if this is a nested, or SAVEPOINT, transaction.

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

attribute sqlalchemy.orm.session.SessionTransaction.parent

The parent SessionTransaction of thisSessionTransaction.

If this attribute is None, indicates thisSessionTransaction is at the top of the stack, and corresponds 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, then this is a SAVEPOINT, and if False, indicates this a subtransaction.

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

Session Utilities

Object Name Description
close_all_sessions() Close all sessions in memory.
make_transient(instance) Alter the state of the given instance so that it is transient.
make_transient_to_detached(instance) Make the given transient instance detached.
object_session(instance) Return the Session to which the given instance belongs.
was_deleted(object_) Return True if the given object was deleted within a session flush.

function sqlalchemy.orm.session.close_all_sessions()

Close all sessions in memory.

This function consults a global registry of all Session objects and calls Session.close() on them, which resets them to a clean state.

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

New in version 1.3.

function sqlalchemy.orm.session.make_transient(instance)

Alter the state of the given instance so that it is transient.

Note

make_transient() is a special-case function for advanced 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. The effect is that the object will behave as though it were newly constructed, except retaining any attribute / collection values that were loaded at the time of the call. The InstanceState.deleted flag is also reset if this object had been deleted as a result of usingSession.delete().

Warning

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

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

function sqlalchemy.orm.session.make_transient_to_detached(instance)

Make the given transient instance detached.

Note

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

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

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

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

New in version 0.9.5.

function sqlalchemy.orm.session.object_session(instance)

Return the Session to which the given instance belongs.

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

function sqlalchemy.orm.util.was_deleted(object_)

Return True if the given object was deleted within a session flush.

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

Attribute and State Management Utilities

These functions are provided by the SQLAlchemy attribute instrumentation API to provide a detailed interface for dealing with instances, attribute values, and history. Some of them are useful when constructing event listener functions, such as those described in ORM Events.

Object Name Description
del_attribute(instance, key) Delete the value of an attribute, firing history events.
flag_dirty(instance) Mark an instance as ‘dirty’ without any specific attribute mentioned.
flag_modified(instance, key) Mark an attribute on an instance as ‘modified’.
get_attribute(instance, key) Get the value of an attribute, firing any callables required.
get_history(obj, key[, passive]) Return a History record for the given object and attribute key.
History A 3-tuple of added, unchanged and deleted values, representing the changes which have occurred on an instrumented attribute.
init_collection(obj, key) Initialize a collection attribute and return the collection adapter.
instance_state Return the InstanceState for a given mapped object.
is_instrumented(instance, key) Return True if the given attribute on the given instance is instrumented by the attributes package.
object_state(instance) Given an object, return the InstanceStateassociated with the object.
set_attribute(instance, key, value[, initiator]) Set the value of an attribute, firing history events.
set_committed_value(instance, key, value) Set the value of an attribute with no history events.

function sqlalchemy.orm.util.object_state(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:

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

function sqlalchemy.orm.attributes.del_attribute(instance, key)

Delete the value of an attribute, firing history events.

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

function sqlalchemy.orm.attributes.get_attribute(instance, key)

Get the value of an attribute, firing any callables required.

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

function sqlalchemy.orm.attributes.get_history(obj, key, passive=symbol('PASSIVE_OFF'))

Return a History record for the given object and attribute key.

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

Parameters:

function sqlalchemy.orm.attributes.init_collection(obj, key)

Initialize a collection attribute and return the collection adapter.

This function is used to provide direct access to collection internals for 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().

Parameters:

function sqlalchemy.orm.attributes.flag_modified(instance, key)

Mark an attribute on an instance as ‘modified’.

This sets the ‘modified’ flag on the instance and establishes 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 attribute so that it is considered within a flush, use theflag_dirty() call.

function sqlalchemy.orm.attributes.flag_dirty(instance)

Mark an instance as ‘dirty’ without any specific attribute mentioned.

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

New in version 1.2.

function sqlalchemy.orm.attributes.instance_state()

Return the InstanceState for a given mapped object.

This function is the internal version of object_state(). Theobject_state() and/or theinspect() function is preferred here as they each emit an informative exception if the given object is not mapped.

function sqlalchemy.orm.instrumentation.is_instrumented(instance, key)

Return True if the given attribute on the given instance is instrumented by the attributes package.

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

function sqlalchemy.orm.attributes.set_attribute(instance, key, value, initiator=None)

Set the value of an attribute, firing history events.

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

Parameters:

function sqlalchemy.orm.attributes.set_committed_value(instance, key, value)

Set the value of an attribute with no history events.

Cancels any previous history present. The value should be a scalar value for scalar-holding attributes, or an iterable for any collection-holding attribute.

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

class sqlalchemy.orm.attributes.History(added, unchanged, deleted)

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

The easiest way to get a History object for a particular attribute 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:

method sqlalchemy.orm.attributes.History.empty()

Return True if this History has no changes and no existing, unchanged state.

method sqlalchemy.orm.attributes.History.has_changes()

Return True if this History has changes.

method sqlalchemy.orm.attributes.History.non_added()

Return a collection of unchanged + deleted.

method sqlalchemy.orm.attributes.History.non_deleted()

Return a collection of added + unchanged.

method sqlalchemy.orm.attributes.History.sum()

Return a collection of added + unchanged + deleted.