Skip to content

Commit 31e34b2

Browse files
committed
refactor: use async_sessionmake factory instead of sessionmaker to create Async Session and add AsyncAttrs to Base Metadata to provide accessor to awaitable attributes (ref: https://docs.sqlalchemy.org/en/20/orm/extensions/asyncio.html#sqlalchemy.ext.asyncio.AsyncAttrs)
1 parent cbdd221 commit 31e34b2

File tree

2 files changed

+9
-10
lines changed

2 files changed

+9
-10
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -139,6 +139,7 @@ venv.bak/
139139

140140
# Rope project settings
141141
.ropeproject
142+
.vscode
142143

143144
# mkdocs documentation
144145
/site

src/labs/db.py

+8-10
Original file line numberDiff line numberDiff line change
@@ -6,10 +6,11 @@
66
77
"""
88

9+
from typing import AsyncGenerator
910
from sqlalchemy.ext.asyncio import create_async_engine,\
10-
AsyncSession
11+
AsyncSession, async_sessionmaker, AsyncAttrs
1112
from sqlalchemy.orm import DeclarativeBase,\
12-
configure_mappers, sessionmaker
13+
configure_mappers
1314

1415

1516
from .settings import settings
@@ -24,19 +25,16 @@
2425
configure_mappers()
2526

2627
# Get an async session from the engine
28+
AsyncSessionFactory = async_sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
2729

2830

29-
async def get_async_session() -> AsyncSession:
30-
async_session = sessionmaker(
31-
engine, class_=AsyncSession, expire_on_commit=False
32-
)
33-
async with async_session() as session:
31+
async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
32+
async with AsyncSessionFactory() as session:
3433
yield session
3534

36-
# Used by the ORM layer to describe models
37-
3835

39-
class Base(DeclarativeBase):
36+
# Used by the ORM layer to describe models
37+
class Base(DeclarativeBase, AsyncAttrs):
4038
"""
4139
SQLAlchemy 2.0 style declarative base class
4240
https://bit.ly/3WE3Srg

0 commit comments

Comments
 (0)