zillow-scraper / app /db /session.py
MuhammadSaad16's picture
Add application file
a8f5b0f
Raw
History Blame Contribute Delete
1.13 kB
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine
from sqlalchemy.orm import DeclarativeBase
from app.core.config import settings
_is_sqlite = settings.DATABASE_URL.startswith("sqlite")
# SQLite doesn't support pool_size / max_overflow / pool_pre_ping
_engine_kwargs: dict = {"echo": settings.DEBUG}
if not _is_sqlite:
_engine_kwargs.update({"pool_size": 10, "max_overflow": 20, "pool_pre_ping": True})
engine = create_async_engine(settings.DATABASE_URL, **_engine_kwargs)
AsyncSessionLocal = async_sessionmaker(
bind=engine,
class_=AsyncSession,
expire_on_commit=False,
autocommit=False,
autoflush=False,
)
class Base(DeclarativeBase):
pass
async def get_db() -> AsyncSession:
async with AsyncSessionLocal() as session:
try:
yield session
await session.commit()
except Exception:
await session.rollback()
raise
finally:
await session.close()
async def init_db() -> None:
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.create_all)