Create a new Session.
Parameters: |
|
---|---|
Returns: | an Session instance |
The defaults of create_session() are the opposite of that of sessionmaker(); autoflush and expire_on_commit are False, autocommit is True. In this sense the session acts more like the “classic” SQLAlchemy 0.3 session with these.
Usage:
>>> from sqlalchemy.orm import create_session
>>> session = create_session()
It is recommended to use sessionmaker() instead of create_session().
Provides thread-local management of Sessions.
This is a front-end function to ScopedSession.
Parameters: |
|
---|---|
Returns: | an ScopedSession instance |
Usage:
Session = scoped_session(sessionmaker(autoflush=True))
To instantiate a Session object which is part of the scoped context, instantiate normally:
session = Session()
Most session methods are available as classmethods from the scoped session:
Session.commit()
Session.close()
Generate a custom-configured Session class.
The returned object is a subclass of Session, which, when instantiated with no arguments, uses the keyword arguments configured here as its constructor arguments.
It is intended that the sessionmaker() function be called within the global scope of an application, and the returned class be made available to the rest of the application as the single class used to instantiate sessions.
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 special classmethod configure(), which allows additional configurational options to take place after the custom Session class has been generated. This is useful particularly for defining the specific Engine (or engines) to which new instances of Session should be bound:
Session = sessionmaker()
Session.configure(bind=create_engine('sqlite:///foo.db'))
sess = Session()
Options:
Parameters: |
|
---|
Manages persistence operations for ORM-mapped objects.
The Session is the front end to SQLAlchemy’s Unit of Work implementation. The concept behind Unit of Work is to track modifications to a field of objects, and then be able to flush those changes to the database in a single operation.
SQLAlchemy’s unit of work includes these functions:
When dealing with instances of mapped classes, an instance may be attached to a particular Session, else it is unattached . An instance also may or may not correspond to an actual row in the database. These conditions break up into four distinct states:
The session methods which control instance state include add(), delete(), merge(), and expunge().
The Session object is generally not threadsafe. A session which is set to autocommit and is only read from may be used by concurrent threads if it’s acceptable that some object instances may be loaded twice.
The typical pattern to managing Sessions in a multi-threaded environment is either to use mutexes to limit concurrent access to one thread at a time, or more commonly to establish a unique session for every thread, using a threadlocal variable. SQLAlchemy provides a thread-managed Session adapter, provided by the scoped_session() function.
Construct a new Session.
Arguments to Session are described using the sessionmaker() function.
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().
Begin a transaction on this Session.
If this Session is already within a transaction, either a plain transaction or nested transaction, an error is raised, unless subtransactions=True or nested=True is specified.
The subtransactions=True flag indicates that this begin() can create a subtransaction if a transaction is already in progress. A subtransaction is a non-transactional, delimiting construct that allows matching begin()/commit() pairs to be nested together, with only the outermost begin/commit pair actually affecting transactional state. When a rollback is issued, the subtransaction will directly roll back the innermost real transaction, however each subtransaction still must be explicitly rolled back to maintain proper stacking of subtransactions.
If no transaction is in progress, then a real transaction is begun.
The nested flag begins a SAVEPOINT transaction and is equivalent to calling begin_nested().
Begin a nested transaction on this Session.
The target database(s) must support SQL SAVEPOINTs or a SQLAlchemy-supported vendor implementation of the idea.
The nested transaction is a real transation, unlike a “subtransaction” which corresponds to multiple begin() calls. The next rollback() or commit() call will operate upon this nested transaction.
Bind operations for a mapper to a Connectable.
All subsequent operations involving this mapper will use the given bind.
Bind operations on a Table to a Connectable.
All subsequent operations involving this Table will use the given bind.
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.
Flush pending changes and commit the current transaction.
If no transaction is in progress, this method raises an InvalidRequestError.
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.
For a session configured with autocommit=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.
Return the active Connection.
Retrieves the Connection managing the current transaction. Any operations executed on the Connection will take place in the same transactional context as Session operations.
For autocommit Sessions with no active manual transaction, connection() is a passthrough to contextual_connect() on the underlying engine.
Ambiguity in multi-bind or unbound Sessions can be resolved through any of the optional keyword arguments. See get_bind() for more information.
Mark an instance as deleted.
The database delete operation occurs upon flush().
The set of all persistent instances considered 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 is_modified() method.
Execute a clause within the current transaction.
Returns a ResultProxy of execution results. autocommit Sessions will create a transaction on the fly.
Connection ambiguity in multi-bind or unbound Sessions will be resolved by inspecting the clause for binds. The ‘mapper’ and ‘instance’ keyword arguments may be used if this is insufficient, See get_bind() for more information.
Expire the attributes on an instance.
Marks the attributes of an instance as out of date. When an expired attribute is next accessed, query will be issued to the database and the attributes will be refreshed with their current database value. expire() is a lazy variant of refresh().
The attribute_names argument is an iterable collection of attribute names indicating a subset of attributes to be expired.
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.
Remove all object instances from this Session.
This is equivalent to calling expunge(obj) on all objects in this Session.
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. 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 int the flush.
Return an engine corresponding to the given arguments.
All arguments are optional.
Return True if instance has modified attributes.
This method retrieves a history instance for each instrumented attribute on the instance and performs a comparison of the current value to its previously committed value. Note that instances present in the ‘dirty’ collection may result in a value of False when tested with this method.
include_collections indicates if multivalued collections should be included in the operation. Setting this to False is a way to detect only local-column based properties (i.e. scalar columns or many-to-one foreign keys) that would result in an UPDATE for this instance upon flush.
The passive flag indicates if unloaded attributes and collections should not be loaded in the course of performing this test.
Copy the state an instance onto the persistent instance with the same identifier.
If there is no persistent instance currently associated with the session, it will be loaded. Return the persistent instance. If the given instance is unsaved, save a copy of and return it as a newly persistent instance. The given instance does not become associated with the session.
This operation cascades to associated instances if the association is mapped with cascade="merge".
Prepare the current transaction in progress for two phase commit.
If no transaction is in progress, this method raises an InvalidRequestError.
Only root transactions of two phase sessions can be prepared. If the current transaction is not such, an InvalidRequestError is raised.
Remove unreferenced instances cached in the identity map.
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.
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.
Parameters: |
|
---|
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 when begin() is called multiple times.
Provides thread-local management of Sessions.
Usage:
Session = scoped_session(sessionmaker(autoflush=True))
... use session normally.
return a mapper() function which associates this ScopedSession with the Mapper.
Session.mapper is deprecated. Please see http://www.sqlalchemy.org/trac/wiki/UsageRecipes/SessionAwareMapper for information on how to replicate its behavior.
DEPRECATED.
return a class property which produces a Query object against the class when called.
Session = scoped_session(sessionmaker())
# after mappers are defined result = MyClass.query.filter(MyClass.name==’foo’).all()
Produces instances of the session’s configured query class by default. To override and use a custom implementation, provide a query_cls callable. The callable will be invoked with the class’s mapper as a positional argument and a session keyword argument.
There is no limit to the number of query properties placed on a class.