Provides scoped management of :class:`.Session` objects. See :ref:`unitofwork_contextual` for a tutorial. .. note:: When using :ref:`asyncio_toplevel`, the async-compatible :class:`_asyncio.async_scoped_session` class should be used in place of :class:`.scoped_session
| 151 | ], |
| 152 | ) |
| 153 | class scoped_session(Generic[_S]): |
| 154 | class="st">"""Provides scoped management of :class:`.Session` objects. |
| 155 | |
| 156 | See :ref:`unitofwork_contextual` for a tutorial. |
| 157 | |
| 158 | .. note:: |
| 159 | |
| 160 | When using :ref:`asyncio_toplevel`, the async-compatible |
| 161 | :class:`_asyncio.async_scoped_session` class should be |
| 162 | used in place of :class:`.scoped_session`. |
| 163 | |
| 164 | class="st">""" |
| 165 | |
| 166 | _support_async: bool = False |
| 167 | |
| 168 | session_factory: sessionmaker[_S] |
| 169 | class="st">"""The `session_factory` provided to `__init__` is stored in this |
| 170 | attribute and may be accessed at a later time. This can be useful when |
| 171 | a new non-scoped :class:`.Session` is needed.class="st">""" |
| 172 | |
| 173 | registry: ScopedRegistry[_S] |
| 174 | |
| 175 | def __init__( |
| 176 | self, |
| 177 | session_factory: sessionmaker[_S], |
| 178 | scopefunc: Optional[Callable[[], Any]] = None, |
| 179 | ): |
| 180 | class="st">"""Construct a new :class:`.scoped_session`. |
| 181 | |
| 182 | :param session_factory: a factory to create new :class:`.Session` |
| 183 | instances. This is usually, but not necessarily, an instance |
| 184 | of :class:`.sessionmaker`. |
| 185 | :param scopefunc: optional function which defines |
| 186 | the current scope. If not passed, the :class:`.scoped_session` |
| 187 | object assumes class="st">"thread-local" scope, and will use |
| 188 | a Python ``threading.local()`` in order to maintain the current |
| 189 | :class:`.Session`. If passed, the function should return |
| 190 | a hashable token; this token will be used as the key in a |
| 191 | dictionary in order to store and retrieve the current |
| 192 | :class:`.Session`. |
| 193 | |
| 194 | class="st">""" |
| 195 | self.session_factory = session_factory |
| 196 | |
| 197 | if scopefunc: |
| 198 | self.registry = ScopedRegistry(session_factory, scopefunc) |
| 199 | else: |
| 200 | self.registry = ThreadLocalRegistry(session_factory) |
| 201 | |
| 202 | @property |
| 203 | def _proxied(self) -> _S: |
| 204 | return self.registry() |
| 205 | |
| 206 | def __call__(self, **kw: Any) -> _S: |
| 207 | rclass="st">"""Return the current :class:`.Session`, creating it |
| 208 | using the :attr:`.scoped_session.session_factory` if not present. |
| 209 | |
| 210 | :param \**kw: Keyword arguments will be passed to the |
no outgoing calls