- Created .env-example for environment variable setup - Updated README to reflect changes in .env file creation - Modified config.py to include new environment variables and DATABASE_URL property - Enhanced database.py with connect and disconnect functions - Updated main.py to manage database connection lifecycle - Adjusted compose.yaml for consistent environment variable usage
23 lines
717 B
Python
23 lines
717 B
Python
from typing import AsyncGenerator
|
|
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession
|
|
from sqlalchemy.orm import sessionmaker
|
|
from app.config import settings
|
|
|
|
engine = create_async_engine(settings.DATABASE_URL, echo=settings.DEBUG)
|
|
AsyncSessionLocal = sessionmaker(engine, class_=AsyncSession, expire_on_commit=False)
|
|
|
|
async def connect():
|
|
pass # engine initializes at module level
|
|
|
|
async def disconnect():
|
|
await engine.dispose()
|
|
|
|
async def get_db() -> AsyncGenerator[AsyncSession, None]:
|
|
async with AsyncSessionLocal() as session:
|
|
try:
|
|
yield session
|
|
await session.commit()
|
|
except Exception:
|
|
await session.rollback()
|
|
raise
|