31 lines
724 B
Python
31 lines
724 B
Python
|
|
"""Databaskonfiguration och session-hantering."""
|
||
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
|
||
|
|
from sqlalchemy.orm import declarative_base
|
||
|
|
from app.config import get_settings
|
||
|
|
|
||
|
|
settings = get_settings()
|
||
|
|
|
||
|
|
engine = create_async_engine(
|
||
|
|
settings.DATABASE_URL,
|
||
|
|
echo=settings.DEBUG,
|
||
|
|
future=True,
|
||
|
|
)
|
||
|
|
|
||
|
|
AsyncSessionLocal = async_sessionmaker(
|
||
|
|
engine,
|
||
|
|
class_=AsyncSession,
|
||
|
|
expire_on_commit=False,
|
||
|
|
autoflush=False,
|
||
|
|
)
|
||
|
|
|
||
|
|
Base = declarative_base()
|
||
|
|
|
||
|
|
|
||
|
|
async def get_db() -> AsyncSession:
|
||
|
|
"""Dependency för FastAPI-endpoints."""
|
||
|
|
async with AsyncSessionLocal() as session:
|
||
|
|
try:
|
||
|
|
yield session
|
||
|
|
finally:
|
||
|
|
await session.close()
|