Skip to content

Commit e45e42e

Browse files
committed
use the proper 'async_sessionmaker' factory
Signed-off-by: Grant Ramsay <seapagan@gmail.com>
1 parent edfd24e commit e45e42e

File tree

2 files changed

+10
-9
lines changed

2 files changed

+10
-9
lines changed

db.py

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,9 @@
1-
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
2-
from sqlalchemy.orm import declarative_base, sessionmaker
1+
"""Set up the database connection and session.""" ""
2+
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
3+
from sqlalchemy.orm import declarative_base
34

45
DATABASE_URL = "postgresql+asyncpg://postgres:postgres@localhost/postgres"
56

67
engine = create_async_engine(DATABASE_URL, echo=False)
78
Base = declarative_base()
8-
9-
10-
async_session = sessionmaker(
11-
engine, class_=AsyncSession, expire_on_commit=False # type: ignore
12-
)
9+
async_session = async_sessionmaker(engine, expire_on_commit=False)

main.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
"""An example of using FastAPI with Async SQLAlchemy 2."""
12
import subprocess
23
from contextlib import asynccontextmanager
34

@@ -29,8 +30,11 @@ async def lifespan(app: FastAPI):
2930

3031

3132
async def get_db():
32-
"""Get a database session."""
33-
async with async_session() as session: # type: ignore
33+
"""Get a database session.
34+
35+
To be used for dependency injection.
36+
"""
37+
async with async_session() as session:
3438
async with session.begin():
3539
yield session
3640

0 commit comments

Comments
 (0)