
- Set up project structure with FastAPI app - Implement SQLAlchemy models and async database connection - Create CRUD endpoints for items resource - Add health endpoint for monitoring - Configure Alembic for database migrations - Create comprehensive documentation generated with BackendIM... (backend.im)
37 lines
877 B
Python
37 lines
877 B
Python
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
|
|
from sqlalchemy.orm import declarative_base, sessionmaker
|
|
from pathlib import Path
|
|
|
|
# Create the database directory
|
|
DB_DIR = Path("/app") / "storage" / "db"
|
|
DB_DIR.mkdir(parents=True, exist_ok=True)
|
|
|
|
# SQLite connection URL
|
|
SQLALCHEMY_DATABASE_URL = f"sqlite+aiosqlite:///{DB_DIR}/db.sqlite"
|
|
|
|
# Create the engine
|
|
engine = create_async_engine(
|
|
SQLALCHEMY_DATABASE_URL,
|
|
connect_args={"check_same_thread": False},
|
|
echo=True,
|
|
)
|
|
|
|
# Session factory
|
|
SessionLocal = sessionmaker(
|
|
autocommit=False,
|
|
autoflush=False,
|
|
bind=engine,
|
|
class_=AsyncSession,
|
|
expire_on_commit=False,
|
|
)
|
|
|
|
# Base class for ORM models
|
|
Base = declarative_base()
|
|
|
|
# Dependency for getting the database session
|
|
async def get_db():
|
|
db = SessionLocal()
|
|
try:
|
|
yield db
|
|
finally:
|
|
await db.close() |