44
44
objects to re-access the database in order to keep synchronized. It is
45
45
possible to "detach" objects from a :class:`.Session`, and to continue using
46
46
them, though this practice has its caveats. It's intended that
47
usually, you'd re-associate detached objects another :class:`.Session` when you
47
usually, you'd re-associate detached objects with another :class:`.Session` when you
48
48
want to work with them again, so that they can resume their normal task of
49
49
representing database state.
56
56
:class:`.Session` is a regular Python class which can
57
57
be directly instantiated. However, to standardize how sessions are configured
58
and acquired, the :func:`.sessionmaker` function is normally
58
and acquired, the :class:`.sessionmaker` class is normally
59
59
used to create a top level :class:`.Session`
60
60
configuration which can then be used throughout an application without the
61
61
need to repeat the configurational arguments.
63
The usage of :func:`.sessionmaker` is illustrated below:
63
The usage of :class:`.sessionmaker` is illustrated below:
65
65
.. sourcecode:: python+sql
82
82
session.add(myobject)
85
Above, the :func:`.sessionmaker` call creates a factory for us,
85
Above, the :class:`.sessionmaker` call creates a factory for us,
86
86
which we assign to the name ``Session``. This factory, when
87
87
called, will create a new :class:`.Session` object using the configurational
88
88
arguments we've given the factory. In this case, as is typical,
89
89
we've configured the factory to specify a particular :class:`.Engine` for
90
90
connection resources.
92
A typical setup will associate the :func:`.sessionmaker` with an :class:`.Engine`,
92
A typical setup will associate the :class:`.sessionmaker` with an :class:`.Engine`,
93
93
so that each :class:`.Session` generated will use this :class:`.Engine`
94
94
to acquire connection resources. This association can
95
95
be set up as in the example above, using the ``bind`` argument.
97
97
When you write your application, place the
98
:func:`.sessionmaker` factory at the global level. This
98
:class:`.sessionmaker` factory at the global level. This
100
100
be used by the rest of the applcation as the source of new :class:`.Session`
101
101
instances, keeping the configuration for how :class:`.Session` objects
102
102
are constructed in one place.
104
The :func:`.sessionmaker` factory can also be used in conjunction with
105
other helpers, which are passed a user-defined :func:`.sessionmaker` that
104
The :class:`.sessionmaker` factory can also be used in conjunction with
105
other helpers, which are passed a user-defined :class:`.sessionmaker` that
106
106
is then maintained by the helper. Some of these helpers are discussed in the
107
107
section :ref:`session_faq_whentocreate`.
109
109
Adding Additional Configuration to an Existing sessionmaker()
110
110
--------------------------------------------------------------
112
A common scenario is where the :func:`.sessionmaker` is invoked
112
A common scenario is where the :class:`.sessionmaker` is invoked
113
113
at module import time, however the generation of one or more :class:`.Engine`
114
instances to be associated with the :func:`.sessionmaker` has not yet proceeded.
115
For this use case, the :func:`.sessionmaker` construct offers the
114
instances to be associated with the :class:`.sessionmaker` has not yet proceeded.
115
For this use case, the :class:`.sessionmaker` construct offers the
116
116
:meth:`.sessionmaker.configure` method, which will place additional configuration
117
directives into an existing :func:`.sessionmaker` that will take place
117
directives into an existing :class:`.sessionmaker` that will take place
118
118
when the construct is invoked::
142
142
source of connectivity, or a :class:`.Session` that should
143
143
have other arguments such as ``expire_on_commit`` established differently from
144
144
what most of the application wants, specific arguments can be passed to the
145
:func:`.sessionmaker` factory's :meth:`.sessionmaker.__call__` method.
145
:class:`.sessionmaker` factory's :meth:`.sessionmaker.__call__` method.
146
146
These arguments will override whatever
147
147
configurations have already been placed, such as below, where a new :class:`.Session`
148
148
is constructed against a specific :class:`.Connection`::
203
203
Session Frequently Asked Questions
204
204
-----------------------------------
206
* When do I make a :func:`.sessionmaker` ?
206
* When do I make a :class:`.sessionmaker` ?
208
208
Just one time, somewhere in your application's global scope. It should be
209
209
looked upon as part of your application's configuration. If your
210
210
application has three .py files in a package, you could, for example,
211
place the :func:`.sessionmaker` line in your ``__init__.py`` file; from
211
place the :class:`.sessionmaker` line in your ``__init__.py`` file; from
212
212
that point on your other modules say "from mypackage import Session". That
213
213
way, everyone else just uses :class:`.Session()`,
214
214
and the configuration of that session is controlled by that central point.
219
219
engine later on, using :meth:`.sessionmaker.configure`.
221
221
In the examples in this section, we will frequently show the
222
:func:`.sessionmaker` being created right above the line where we actually
222
:class:`.sessionmaker` being created right above the line where we actually
223
223
invoke :class:`.Session`. But that's just for
224
example's sake! In reality, the :func:`.sessionmaker` would be somewhere
224
example's sake! In reality, the :class:`.sessionmaker` would be somewhere
225
225
at the module level. The calls to instantiate :class:`.Session`
226
226
would then be placed at the point in the application where database
227
227
conversations begin.
306
306
In those situations where integration libraries are not available,
307
307
SQLAlchemy includes its own "helper" class known as
308
:class:`.ScopedSession`. A tutorial on the usage of this object
308
:class:`.scoped_session`. A tutorial on the usage of this object
309
309
is at :ref:`unitofwork_contextual`. It provides both a quick way
310
310
to associate a :class:`.Session` with the current thread, as well as
311
311
patterns to associate :class:`.Session` objects with other kinds of
351
351
The :class:`.Session` is not designed to be a
352
352
global object from which everyone consults as a "registry" of objects.
353
353
That's more the job of a **second level cache**. SQLAlchemy provides
354
a pattern for implementing second level caching using `Beaker <http://beaker.groovie.org/>`_,
354
a pattern for implementing second level caching using `dogpile.cache <http://dogpilecache.readthedocs.org/>`_,
355
355
via the :ref:`examples_caching` example.
357
357
* How can I get the :class:`~sqlalchemy.orm.session.Session` for a certain object ?
808
812
attribute access or by them being present in a
809
813
:class:`~sqlalchemy.orm.query.Query` result set, they receive the most recent
810
814
state. To disable this behavior, configure
811
:func:`.sessionmaker` with ``expire_on_commit=False``.
815
:class:`.sessionmaker` with ``expire_on_commit=False``.
813
817
Normally, instances loaded into the :class:`~sqlalchemy.orm.session.Session`
814
818
are never changed by subsequent queries; the assumption is that the current
993
999
full flush, these collections are all empty, and all objects are again weakly
994
1000
referenced. To disable the weak referencing behavior and force all objects
995
1001
within the session to remain until explicitly expunged, configure
996
:func:`.sessionmaker` with the ``weak_identity_map=False``
1002
:class:`.sessionmaker` with the ``weak_identity_map=False``
999
1005
.. _unitofwork_cascades:
1170
1176
So above, the assignment of ``i1.order = o1`` will append ``i1`` to the ``items``
1171
1177
collection of ``o1``, but will not add ``i1`` to the session. You can, of
1172
course, :meth:`~.Session.add` ``i1`` to the session at a later point. This option
1173
may be helpful for situations where an object needs to be kept out of a
1178
course, :meth:`~.Session.add` ``i1`` to the session at a later point. This
1179
option may be helpful for situations where an object needs to be kept out of a
1174
1180
session until it's construction is completed, but still needs to be given
1175
1181
associations to objects which are already persistent in the target session.
1311
1318
still occurs within the scope of a single transaction, though this transaction
1312
1319
is closed out after the :meth:`.Session.flush` operation completes.
1314
"autocommit" mode should **not be considered for general use**. While
1315
very old versions of SQLAlchemy standardized on this mode, the modern
1316
:class:`.Session` benefits highly from being given a clear point of transaction
1317
demarcation via :meth:`.Session.rollback` and :meth:`.Session.commit`.
1318
The autoflush action can safely emit SQL to the database as needed without
1319
implicitly producing permanent effects, the contents of attributes
1320
are expired only when a logical series of steps has completed. If the
1321
:class:`.Session` were to be used in pure "autocommit" mode without
1322
an ongoing transaction, these features should be disabled, that is,
1323
``autoflush=False, expire_on_commit=False``.
1323
"autocommit" mode should **not be considered for general use**.
1324
If used, it should always be combined with the usage of
1325
:meth:`.Session.begin` and :meth:`.Session.commit`, to ensure
1326
a transaction demarcation.
1328
Executing queries outside of a demarcated transaction is a legacy mode
1329
of usage, and can in some cases lead to concurrent connection
1332
In the absense of a demarcated transaction, the :class:`.Session`
1333
cannot make appropriate decisions as to when autoflush should
1334
occur nor when auto-expiration should occur, so these features
1335
should be disabled with ``autoflush=False, expire_on_commit=False``.
1325
1337
Modern usage of "autocommit" is for framework integrations that need to control
1326
1338
specifically when the "begin" state occurs. A session which is configured with
1361
1372
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
1363
1374
A subtransaction indicates usage of the :meth:`.Session.begin` method in conjunction with
1364
the ``subtransactions=True`` flag. This produces a a non-transactional, delimiting construct that
1375
the ``subtransactions=True`` flag. This produces a non-transactional, delimiting construct that
1365
1376
allows nesting of calls to :meth:`~.Session.begin` and :meth:`~.Session.commit`.
1366
1377
It's purpose is to allow the construction of code that can function within a transaction
1367
1378
both independently of any external code that starts a transaction,
1468
1479
:class:`~sqlalchemy.orm.session.Session` within its transactional context.
1469
1480
This is most easily accomplished using the
1470
1481
:meth:`~.Session.execute` method, which returns a
1471
:class:`~sqlalchemy.engine.base.ResultProxy` in the same manner as an
1472
:class:`~sqlalchemy.engine.base.Engine` or
1473
:class:`~sqlalchemy.engine.base.Connection`::
1482
:class:`~sqlalchemy.engine.ResultProxy` in the same manner as an
1483
:class:`~sqlalchemy.engine.Engine` or
1484
:class:`~sqlalchemy.engine.Connection`::
1475
1486
Session = sessionmaker(bind=engine)
1476
1487
session = Session()
1481
1492
# execute a SQL expression construct
1482
1493
result = session.execute(select([mytable]).where(mytable.c.id==7))
1484
The current :class:`~sqlalchemy.engine.base.Connection` held by the
1495
The current :class:`~sqlalchemy.engine.Connection` held by the
1485
1496
:class:`~sqlalchemy.orm.session.Session` is accessible using the
1486
1497
:meth:`~.Session.connection` method::
1488
1499
connection = session.connection()
1490
1501
The examples above deal with a :class:`~sqlalchemy.orm.session.Session` that's
1491
bound to a single :class:`~sqlalchemy.engine.base.Engine` or
1492
:class:`~sqlalchemy.engine.base.Connection`. To execute statements using a
1502
bound to a single :class:`~sqlalchemy.engine.Engine` or
1503
:class:`~sqlalchemy.engine.Connection`. To execute statements using a
1493
1504
:class:`~sqlalchemy.orm.session.Session` which is bound either to multiple
1494
1505
engines, or none at all (i.e. relies upon bound metadata), both
1495
1506
:meth:`~.Session.execute` and
1580
1591
of user-defined :class:`.Session` scopes. It is also used by third-party
1581
1592
integration systems to help construct their integration schemes.
1583
The object is the :class:`.ScopedSession` object, and it represents a
1594
The object is the :class:`.scoped_session` object, and it represents a
1584
1595
**registry** of :class:`.Session` objects. If you're not familiar with the
1585
1596
registry pattern, a good introduction can be found in `Patterns of Enterprise
1586
1597
Architecture <http://martinfowler.com/eaaCatalog/registry.html>`_.
1590
The :class:`.ScopedSession` object is a very popular and useful object
1601
The :class:`.scoped_session` object is a very popular and useful object
1591
1602
used by many SQLAlchemy applications. However, it is important to note
1592
1603
that it presents **only one approach** to the issue of :class:`.Session`
1593
1604
management. If you're new to SQLAlchemy, and especially if the
1596
1607
system such as `Flask-SQLAlchemy <http://packages.python.org/Flask-SQLAlchemy/>`_
1597
1608
or `zope.sqlalchemy <http://pypi.python.org/pypi/zope.sqlalchemy>`_.
1599
A :class:`.ScopedSession` is constructed by calling the :func:`.scoped_session`
1600
function, passing it a
1610
A :class:`.scoped_session` is constructed by calling it, passing it a
1601
1611
**factory** which can create new :class:`.Session` objects. A factory
1602
1612
is just something that produces a new object when called, and in the
1603
case of :class:`.Session`, the most common factory is the :func:`.sessionmaker`,
1613
case of :class:`.Session`, the most common factory is the :class:`.sessionmaker`,
1604
1614
introduced earlier in this section. Below we illustrate this usage::
1606
1616
>>> from sqlalchemy.orm import scoped_session
1609
1619
>>> session_factory = sessionmaker(bind=some_engine)
1610
1620
>>> Session = scoped_session(session_factory)
1612
The :class:`.ScopedSession` object we've created will now call upon the
1613
:func:`.sessionmaker` when we "call" the registry::
1622
The :class:`.scoped_session` object we've created will now call upon the
1623
:class:`.sessionmaker` when we "call" the registry::
1615
1625
>>> some_session = Session()
1617
1627
Above, ``some_session`` is an instance of :class:`.Session`, which we
1618
1628
can now use to talk to the database. This same :class:`.Session` is also
1619
present within the :class:`.ScopedSession` registry we've created. If
1629
present within the :class:`.scoped_session` registry we've created. If
1620
1630
we call upon the registry a second time, we get back the **same** :class:`.Session`::
1622
1632
>>> some_other_session = Session()
1626
1636
This pattern allows disparate sections of the application to call upon a global
1627
:class:`.ScopedSession`, so that all those areas may share the same session
1637
:class:`.scoped_session`, so that all those areas may share the same session
1628
1638
without the need to pass it explicitly. The :class:`.Session` we've established
1629
1639
in our registry will remain, until we explicitly tell our regsitry to dispose of it,
1630
by calling :meth:`.ScopedSession.remove`::
1640
by calling :meth:`.scoped_session.remove`::
1632
1642
>>> Session.remove()
1634
The :meth:`.ScopedSession.remove` method first calls :meth:`.Session.close` on
1644
The :meth:`.scoped_session.remove` method first calls :meth:`.Session.close` on
1635
1645
the current :class:`.Session`, which has the effect of releasing any connection/transactional
1636
1646
resources owned by the :class:`.Session` first, then discarding the :class:`.Session`
1637
itself. "Releasing" here means that any pending transaction will be rolled back
1638
using ``connection.rollback()``.
1647
itself. "Releasing" here means that connections are returned to their connection pool and any transactional state is rolled back, ultimately using the ``rollback()`` method of the underlying DBAPI connection.
1640
At this point, the :class:`.ScopedSession` object is "empty", and will create
1649
At this point, the :class:`.scoped_session` object is "empty", and will create
1641
1650
a **new** :class:`.Session` when called again. As illustrated below, this
1642
1651
is not the same :class:`.Session` we had before::
1652
1661
Implicit Method Access
1653
1662
----------------------
1655
The job of the :class:`.ScopedSession` is simple; hold onto a :class:`.Session`
1664
The job of the :class:`.scoped_session` is simple; hold onto a :class:`.Session`
1656
1665
for all who ask for it. As a means of producing more transparent access to this
1657
:class:`.Session`, the :class:`.ScopedSession` also includes **proxy behavior**,
1666
:class:`.Session`, the :class:`.scoped_session` also includes **proxy behavior**,
1658
1667
meaning that the registry itself can be treated just like a :class:`.Session`
1659
1668
directly; when methods are called on this object, they are **proxied** to the
1660
1669
underlying :class:`.Session` being maintained by the registry::
1679
1688
global object will be accessed by many threads concurrently. The :class:`.Session`
1680
1689
object is entirely designed to be used in a **non-concurrent** fashion, which
1681
1690
in terms of multithreading means "only in one thread at a time". So our
1682
above example of :class:`.ScopedSession` usage, where the same :class:`.Session`
1691
above example of :class:`.scoped_session` usage, where the same :class:`.Session`
1683
1692
object is maintained across multiple calls, suggests that some process needs
1684
1693
to be in place such that mutltiple calls across many threads don't actually get
1685
1694
a handle to the same session. We call this notion **thread local storage**,
1686
1695
which means, a special object is used that will maintain a distinct object
1687
1696
per each application thread. Python provides this via the
1688
1697
`threading.local() <http://docs.python.org/library/threading.html#threading.local>`_
1689
construct. The :class:`.ScopedSession` object by default uses this object
1698
construct. The :class:`.scoped_session` object by default uses this object
1690
1699
as storage, so that a single :class:`.Session` is maintained for all who call
1691
upon the :class:`.ScopedSession` registry, but only within the scope of a single
1700
upon the :class:`.scoped_session` registry, but only within the scope of a single
1692
1701
thread. Callers who call upon the registry in a different thread get a
1693
1702
:class:`.Session` instance that is local to that other thread.
1695
Using this technique, the :class:`.ScopedSession` provides a quick and relatively
1704
Using this technique, the :class:`.scoped_session` provides a quick and relatively
1696
1705
simple (if one is familiar with thread-local storage) way of providing
1697
1706
a single, global object in an application that is safe to be called upon
1698
1707
from multiple threads.
1700
The :meth:`.ScopedSession.remove` method, as always, removes the current
1709
The :meth:`.scoped_session.remove` method, as always, removes the current
1701
1710
:class:`.Session` associated with the thread, if any. However, one advantage of the
1702
1711
``threading.local()`` object is that if the application thread itself ends, the
1703
1712
"storage" for that thread is also garbage collected. So it is in fact "safe" to
1704
1713
use thread local scope with an application that spawns and tears down threads,
1705
without the need to call :meth:`.ScopedSession.remove`. However, the scope
1714
without the need to call :meth:`.scoped_session.remove`. However, the scope
1706
1715
of transactions themselves, i.e. ending them via :meth:`.Session.commit` or
1707
1716
:meth:`.Session.rollback`, will usually still be something that must be explicitly
1708
1717
arranged for at the appropriate time, unless the application actually ties the
1727
1736
:class:`.Session` with a thread implies it is also associated with the web request
1728
1737
running within that thread, and vice versa, provided that the :class:`.Session` is
1729
1738
created only after the web request begins and torn down just before the web request ends.
1730
So it is a common practice to use :class:`.ScopedSession` as a quick way
1739
So it is a common practice to use :class:`.scoped_session` as a quick way
1731
1740
to integrate the :class:`.Session` with a web application. The sequence
1732
1741
diagram below illustrates this flow::
1765
1774
Using the above flow, the process of integrating the :class:`.Session` with the
1766
1775
web application has exactly two requirements:
1768
1. Create a single :class:`.ScopedSession` registry when the web application
1777
1. Create a single :class:`.scoped_session` registry when the web application
1769
1778
first starts, ensuring that this object is accessible by the rest of the
1771
2. Ensure that :meth:`.ScopedSession.remove` is called when the web request ends,
1780
2. Ensure that :meth:`.scoped_session.remove` is called when the web request ends,
1772
1781
usually by integrating with the web framework's event system to establish
1773
1782
an "on request end" event.
1776
1785
with a web framework, one which in particular makes the significant assumption
1777
1786
that the **web framework associates web requests with application threads**. It is
1778
1787
however **strongly recommended that the integration tools provided with the web framework
1779
itself be used, if available**, instead of :class:`.ScopedSession`.
1788
itself be used, if available**, instead of :class:`.scoped_session`.
1781
1790
In particular, while using a thread local can be convenient, it is preferable that the :class:`.Session` be
1782
1791
associated **directly with the request**, rather than with
1783
1792
the current thread. The next section on custom scopes details a more advanced configuration
1784
which can combine the usage of :class:`.ScopedSession` with direct request based scope, or
1793
which can combine the usage of :class:`.scoped_session` with direct request based scope, or
1785
1794
any kind of scope.
1787
1796
Using Custom Created Scopes
1788
1797
---------------------------
1790
The :class:`.ScopedSession` object's default behavior of "thread local" scope is only
1799
The :class:`.scoped_session` object's default behavior of "thread local" scope is only
1791
1800
one of many options on how to "scope" a :class:`.Session`. A custom scope can be defined
1792
1801
based on any existing system of getting at "the current thing we are working with".
1795
1804
built using this framework can call this function at any time, and the result will be
1796
1805
some kind of ``Request`` object that represents the current request being processed.
1797
1806
If the ``Request`` object is hashable, then this function can be easily integrated with
1798
:class:`.ScopedSession` to associate the :class:`.Session` with the request. Below we illustrate
1807
:class:`.scoped_session` to associate the :class:`.Session` with the request. Below we illustrate
1799
1808
this in conjunction with a hypothetical event marker provided by the web framework
1800
1809
``on_request_end``, which allows code to be invoked whenever a request ends::
1808
1817
def remove_session(req):
1809
1818
Session.remove()
1811
Above, we instantiate :class:`.ScopedSession` in the usual way, except that we pass
1812
our request-returning function as the "scopefunc". This instructs :class:`.ScopedSession`
1820
Above, we instantiate :class:`.scoped_session` in the usual way, except that we pass
1821
our request-returning function as the "scopefunc". This instructs :class:`.scoped_session`
1813
1822
to use this function to generate a dictionary key whenever the registry is called upon
1814
1823
to return the current :class:`.Session`. In this case it is particularly important
1815
1824
that we ensure a reliable "remove" system is implemented, as this dictionary is not
1941
1955
instrumentation API to provide a detailed interface for dealing
1942
1956
with instances, attribute values, and history. Some of them
1943
1957
are useful when constructing event listener functions, such as
1944
those described in :ref:`events_orm_toplevel`.
1958
those described in :doc:`/orm/events`.
1960
.. currentmodule:: sqlalchemy.orm.util
1962
.. autofunction:: object_state
1946
1964
.. currentmodule:: sqlalchemy.orm.attributes
1958
1976
.. function:: instance_state
1960
Return the :class:`.InstanceState` for a given object.
1962
.. autofunction:: is_instrumented
1964
.. function:: manager_of_class
1966
Return the :class:`.ClassManager` for a given class.
1978
Return the :class:`.InstanceState` for a given
1981
This function is the internal version
1982
of :func:`.object_state`. The
1983
:func:`.object_state` and/or the
1984
:func:`.inspect` function is preferred here
1985
as they each emit an informative exception
1986
if the given object is not mapped.
1988
.. autofunction:: sqlalchemy.orm.instrumentation.is_instrumented
1968
1990
.. autofunction:: set_attribute