diff options
author | Mike Bayer <mike_mp@zzzcomputing.com> | 2023-05-05 11:50:29 -0400 |
---|---|---|
committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2023-05-08 11:50:03 -0400 |
commit | b3216486c417f7fb2abc0724563a1d21f9a835d9 (patch) | |
tree | 56dd6446748c7dc837b2c6e4b2aa8eb6e559a1a2 /examples/asyncio/async_orm.py | |
parent | dc60e7a7d35a470c09ce590f37e949ff8e8cdcde (diff) | |
download | sqlalchemy-b3216486c417f7fb2abc0724563a1d21f9a835d9.tar.gz |
add AsyncAttrs
Added a new helper mixin :class:`_asyncio.AsyncAttrs` that seeks to improve
the use of lazy-loader and other expired or deferred ORM attributes with
asyncio, providing a simple attribute accessor that provides an ``await``
interface to any ORM attribute, whether or not it needs to emit SQL.
Change-Id: I1427b288dc28319c854372643066c491b9ee8dc0
References: #9731
Diffstat (limited to 'examples/asyncio/async_orm.py')
-rw-r--r-- | examples/asyncio/async_orm.py | 15 |
1 files changed, 11 insertions, 4 deletions
diff --git a/examples/asyncio/async_orm.py b/examples/asyncio/async_orm.py index 66501e545..eabc0250d 100644 --- a/examples/asyncio/async_orm.py +++ b/examples/asyncio/async_orm.py @@ -12,15 +12,18 @@ from typing import Optional from sqlalchemy import ForeignKey from sqlalchemy import func from sqlalchemy.ext.asyncio import async_sessionmaker +from sqlalchemy.ext.asyncio import AsyncAttrs from sqlalchemy.ext.asyncio import create_async_engine from sqlalchemy.future import select -from sqlalchemy.orm import declarative_base +from sqlalchemy.orm import DeclarativeBase from sqlalchemy.orm import Mapped from sqlalchemy.orm import mapped_column from sqlalchemy.orm import relationship from sqlalchemy.orm import selectinload -Base = declarative_base() + +class Base(AsyncAttrs, DeclarativeBase): + pass class A(Base): @@ -31,7 +34,7 @@ class A(Base): create_date: Mapped[datetime.datetime] = mapped_column( server_default=func.now() ) - bs: Mapped[List[B]] = relationship(lazy="raise") + bs: Mapped[List[B]] = relationship() class B(Base): @@ -93,11 +96,15 @@ async def async_main(): result = await session.scalars(select(A).order_by(A.id)) - a1 = result.first() + a1 = result.one() a1.data = "new data" await session.commit() + # use the AsyncAttrs interface to accommodate for a lazy load + for b1 in await a1.awaitable_attrs.bs: + print(b1) + asyncio.run(async_main()) |