You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

102 lines
2.8KB

  1. # ext/asyncio/scoping.py
  2. # Copyright (C) 2005-2021 the SQLAlchemy authors and contributors
  3. # <see AUTHORS file>
  4. #
  5. # This module is part of SQLAlchemy and is released under
  6. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  7. from .session import AsyncSession
  8. from ...orm.scoping import ScopedSessionMixin
  9. from ...util import create_proxy_methods
  10. from ...util import ScopedRegistry
  11. @create_proxy_methods(
  12. AsyncSession,
  13. ":class:`_asyncio.AsyncSession`",
  14. ":class:`_asyncio.scoping.async_scoped_session`",
  15. classmethods=["close_all", "object_session", "identity_key"],
  16. methods=[
  17. "__contains__",
  18. "__iter__",
  19. "add",
  20. "add_all",
  21. "begin",
  22. "begin_nested",
  23. "close",
  24. "commit",
  25. "connection",
  26. "delete",
  27. "execute",
  28. "expire",
  29. "expire_all",
  30. "expunge",
  31. "expunge_all",
  32. "flush",
  33. "get",
  34. "get_bind",
  35. "is_modified",
  36. "merge",
  37. "refresh",
  38. "rollback",
  39. "scalar",
  40. ],
  41. attributes=[
  42. "bind",
  43. "dirty",
  44. "deleted",
  45. "new",
  46. "identity_map",
  47. "is_active",
  48. "autoflush",
  49. "no_autoflush",
  50. "info",
  51. ],
  52. )
  53. class async_scoped_session(ScopedSessionMixin):
  54. """Provides scoped management of :class:`.AsyncSession` objects.
  55. See the section :ref:`asyncio_scoped_session` for usage details.
  56. .. versionadded:: 1.4.19
  57. """
  58. def __init__(self, session_factory, scopefunc):
  59. """Construct a new :class:`_asyncio.async_scoped_session`.
  60. :param session_factory: a factory to create new :class:`_asyncio.AsyncSession`
  61. instances. This is usually, but not necessarily, an instance
  62. of :class:`_orm.sessionmaker` which itself was passed the
  63. :class:`_asyncio.AsyncSession` to its :paramref:`_orm.sessionmaker.class_`
  64. parameter::
  65. async_session_factory = sessionmaker(some_async_engine, class_= AsyncSession)
  66. AsyncSession = async_scoped_session(async_session_factory, scopefunc=current_task)
  67. :param scopefunc: function which defines
  68. the current scope. A function such as ``asyncio.current_task``
  69. may be useful here.
  70. """ # noqa E501
  71. self.session_factory = session_factory
  72. self.registry = ScopedRegistry(session_factory, scopefunc)
  73. @property
  74. def _proxied(self):
  75. return self.registry()
  76. async def remove(self):
  77. """Dispose of the current :class:`.AsyncSession`, if present.
  78. Different from scoped_session's remove method, this method would use
  79. await to wait for the close method of AsyncSession.
  80. """
  81. if self.registry.has():
  82. await self.registry().close()
  83. self.registry.clear()