A configurable :class:`.AsyncSession` factory. The :class:`.async_sessionmaker` factory works in the same way as the :class:`.sessionmaker` factory, to generate new :class:`.AsyncSession` objects when called, creating them given the configurational arguments established here. e
| 1668 | |
| 1669 | |
| 1670 | class async_sessionmaker(Generic[_AS]): |
| 1671 | """A configurable :class:`.AsyncSession` factory. |
| 1672 | |
| 1673 | The :class:`.async_sessionmaker` factory works in the same way as the |
| 1674 | :class:`.sessionmaker` factory, to generate new :class:`.AsyncSession` |
| 1675 | objects when called, creating them given |
| 1676 | the configurational arguments established here. |
| 1677 | |
| 1678 | e.g.:: |
| 1679 | |
| 1680 | from sqlalchemy.ext.asyncio import create_async_engine |
| 1681 | from sqlalchemy.ext.asyncio import AsyncSession |
| 1682 | from sqlalchemy.ext.asyncio import async_sessionmaker |
| 1683 | |
| 1684 | |
| 1685 | async def run_some_sql( |
| 1686 | async_session: async_sessionmaker[AsyncSession], |
| 1687 | ) -> None: |
| 1688 | async with async_session() as session: |
| 1689 | session.add(SomeObject(data="object")) |
| 1690 | session.add(SomeOtherObject(name="other object")) |
| 1691 | await session.commit() |
| 1692 | |
| 1693 | |
| 1694 | async def main() -> None: |
| 1695 | # an AsyncEngine, which the AsyncSession will use for connection |
| 1696 | # resources |
| 1697 | engine = create_async_engine( |
| 1698 | "postgresql+asyncpg://scott:tiger@localhost/" |
| 1699 | ) |
| 1700 | |
| 1701 | # create a reusable factory for new AsyncSession instances |
| 1702 | async_session = async_sessionmaker(engine) |
| 1703 | |
| 1704 | await run_some_sql(async_session) |
| 1705 | |
| 1706 | await engine.dispose() |
| 1707 | |
| 1708 | The :class:`.async_sessionmaker` is useful so that different parts |
| 1709 | of a program can create new :class:`.AsyncSession` objects with a |
| 1710 | fixed configuration established up front. Note that :class:`.AsyncSession` |
| 1711 | objects may also be instantiated directly when not using |
| 1712 | :class:`.async_sessionmaker`. |
| 1713 | |
| 1714 | .. versionadded:: 2.0 :class:`.async_sessionmaker` provides a |
| 1715 | :class:`.sessionmaker` class that's dedicated to the |
| 1716 | :class:`.AsyncSession` object, including pep-484 typing support. |
| 1717 | |
| 1718 | .. seealso:: |
| 1719 | |
| 1720 | :ref:`asyncio_orm` - shows example use |
| 1721 | |
| 1722 | :class:`.sessionmaker` - general overview of the |
| 1723 | :class:`.sessionmaker` architecture |
| 1724 | |
| 1725 | |
| 1726 | :ref:`session_getting` - introductory text on creating |
| 1727 | sessions using :class:`.sessionmaker`. |
no outgoing calls