em1tao

Untitled

Jun 24th, 2024
624
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.60 KB | None | 0 0
  1. # session_factory.py
  2. from collections.abc import AsyncGenerator
  3.  
  4. from sqlalchemy.ext.asyncio import (
  5.     AsyncSession,
  6.     async_sessionmaker,
  7.     create_async_engine,
  8.     AsyncEngine,
  9. )
  10.  
  11.  
  12. class SessionFactory:
  13.     def __init__(self, postgres_url: str):
  14.         self.engine: AsyncEngine = create_async_engine(postgres_url, echo=False)
  15.         self.async_session_maker: async_sessionmaker[AsyncSession] = async_sessionmaker(
  16.             self.engine,
  17.             class_=AsyncSession,
  18.             expire_on_commit=False,
  19.         )
  20.  
  21.     async def dispose(self) -> None:
  22.         await self.engine.dispose()
  23.  
  24.     async def __call__(self) -> AsyncGenerator[AsyncSession, None]:
  25.         async with self.async_session_maker() as session:
  26.             yield session
  27.  
  28. # database.py
  29. from collections.abc import AsyncGenerator
  30.  
  31. from sqlalchemy.ext.asyncio import AsyncSession
  32. from sqlalchemy.orm import DeclarativeBase
  33. from sqlalchemy import MetaData
  34. import contextlib
  35. from src.session_factory import SessionFactory
  36.  
  37.  
  38. class Base(DeclarativeBase):
  39.     metadata = MetaData()
  40.  
  41.  
  42. session_factory: SessionFactory | None = None
  43.  
  44.  
  45. async def get_async_session() -> AsyncGenerator[AsyncSession, None]:
  46.     if session_factory is None:
  47.         raise RuntimeError("SessionFactory is not initialized")
  48.     async for session in session_factory():
  49.         yield session
  50.  
  51.  
  52. async def get_db_stub():
  53.     raise NotImplementedError
  54.  
  55. # main.py
  56.  
  57. @asynccontextmanager
  58. async def lifespan(app: FastAPI):
  59.     db.session_factory = SessionFactory(settings.db.url_postgres)
  60.     yield
  61.     await db.session_factory.dispose()
Advertisement
Add Comment
Please, Sign In to add comment