From dcf60f408235239c3e739006b2f1b6d9edf45c4c Mon Sep 17 00:00:00 2001 From: ZTatman Date: Fri, 24 Apr 2026 13:27:58 -0400 Subject: [PATCH] Add FastAPI lifespan pattern with async SQLAlchemy and Docker setup - Move get_db to main.py for cleaner separation of concerns - Remove engine/sessionmaker from database.py (keep only Base class) - Fix config.py: add +asyncpg to database_url, remove @dataclass - Add lifespan context manager for engine lifecycle - Add docker-compose.yml for web + postgres services - Add web/Dockerfile for containerized FastAPI app - Add web/.env.example as environment template --- docker-compose.yml | 29 +++++++++++++++++++++++++++++ web/.env.example | 9 +++++++++ web/Dockerfile | 14 ++++++++++++++ web/app/config.py | 15 +++------------ web/app/database.py | 29 +---------------------------- web/app/main.py | 37 +++++++++++++++++++++++++++++++++++-- 6 files changed, 91 insertions(+), 42 deletions(-) create mode 100644 docker-compose.yml create mode 100644 web/.env.example create mode 100644 web/Dockerfile diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..759c4e0 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,29 @@ +services: + web: + build: + context: ./web + dockerfile: Dockerfile + ports: + - "8000:8000" + environment: + - DATABASE_URL=postgresql+asyncpg://myst:myst@db:5432/myst_db + depends_on: + db: + condition: service_healthy + + db: + image: postgres:16-alpine + environment: + POSTGRES_USER: myst + POSTGRES_PASSWORD: myst + POSTGRES_DB: myst_db + volumes: + - postgres_data:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U myst -d myst"] + interval: 5s + timeout: 5s + retries: 5 + +volumes: + postgres_data: \ No newline at end of file diff --git a/web/.env.example b/web/.env.example new file mode 100644 index 0000000..188fdee --- /dev/null +++ b/web/.env.example @@ -0,0 +1,9 @@ +# Application +APP_NAME=Myst + +# Database (Docker Compose auto-configures this) +DATABASE_URL=postgresql+asyncpg://myst:myst@db:5432/myst_db + +# Forgejo +FORGEJO_BASE_URL= +FORGEJO_PAT= \ No newline at end of file diff --git a/web/Dockerfile b/web/Dockerfile new file mode 100644 index 0000000..4f8e31c --- /dev/null +++ b/web/Dockerfile @@ -0,0 +1,14 @@ +FROM python:3.13-slim + +WORKDIR /app + +COPY --from=ghcr.io/astral-sh/uv:latest /uv /usr/local/bin/uv + +COPY pyproject.toml uv.lock ./ +RUN uv sync --frozen + +COPY . . + +EXPOSE 8000 + +CMD ["uv", "run", "uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"] \ No newline at end of file diff --git a/web/app/config.py b/web/app/config.py index 366a990..39f35f4 100644 --- a/web/app/config.py +++ b/web/app/config.py @@ -1,4 +1,3 @@ -from dataclasses import dataclass from functools import lru_cache from pathlib import Path @@ -7,19 +6,11 @@ from pydantic_settings import BaseSettings, SettingsConfigDict env_file = Path(__file__).parent.parent / ".env" -@dataclass class Settings(BaseSettings): - """Settings for the Myst application. - - Args: - app_name (str): The name of the application. - database_url (str): The URL of the database. - forgejo_base_url (str): The base URL of the Forgejo instance. - forgejo_pat (str): The Forgejo personal access token. - """ + """Application settings loaded from environment variables.""" app_name: str = "Myst" - database_url: str = "postgresql://myst:myst@db:5432/myst_db" + database_url: str = "postgresql+asyncpg://myst:myst@db:5432/myst_db" forgejo_base_url: str = "" forgejo_pat: str = "" @@ -28,5 +19,5 @@ class Settings(BaseSettings): @lru_cache def get_settings() -> Settings: - """Get the settings for the application.""" + """Cached settings instance.""" return Settings() diff --git a/web/app/database.py b/web/app/database.py index b5b7f09..3859649 100644 --- a/web/app/database.py +++ b/web/app/database.py @@ -1,37 +1,10 @@ import datetime -from typing import AsyncGenerator -from sqlalchemy.ext.asyncio import ( - AsyncAttrs, - AsyncSession, - async_sessionmaker, - create_async_engine, -) from sqlalchemy.orm import DeclarativeBase from sqlalchemy.types import DateTime -# Database engine setup -engine = create_async_engine( - url="postgresql+asyncpg://myst:myst@db:5432/myst_db", - connect_args={"connect_same_thread": False}, - echo=True, -) -# Session factory setup -create_async_session = async_sessionmaker( - bind=engine, - autoflush=False, - autocommit=False, -) - - -# Base class for declarative models -class Base(AsyncAttrs, DeclarativeBase): +class Base(DeclarativeBase): type_annotations_map = { datetime.datetime: DateTime(timezone=True), } - - -async def get_db() -> AsyncGenerator[AsyncSession, None]: - async with create_async_session() as session: - yield session diff --git a/web/app/main.py b/web/app/main.py index 3605be3..717402f 100644 --- a/web/app/main.py +++ b/web/app/main.py @@ -1,8 +1,41 @@ -from fastapi import FastAPI +from contextlib import asynccontextmanager +from typing import AsyncGenerator +from fastapi import FastAPI +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine + +from app.config import get_settings +from app.database import Base from app.routers import links -app = FastAPI(title="Myst") + +@asynccontextmanager +async def lifespan(app: FastAPI): + """Manage database engine lifecycle.""" + settings = get_settings() + engine = create_async_engine( + url=settings.database_url, + pool_pre_ping=True, + echo=settings.app_name != "Myst", + ) + app.state.db_session = async_sessionmaker( + engine, + class_=AsyncSession, + expire_on_commit=False, # Prevents MissingGreenlet in async + ) + async with engine.begin() as conn: + await conn.run_sync(Base.metadata.create_all) # Create all tables on startup + yield + await engine.dispose() # Close all connections on shutdown + + +async def get_db() -> AsyncGenerator[AsyncSession, None]: + """Dependency that provides a database session.""" + async with app.state.db_session() as session: + yield session + + +app = FastAPI(lifespan=lifespan) app.include_router(links.router)