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
This commit is contained in:
parent
36c6231266
commit
dcf60f4082
6 changed files with 91 additions and 42 deletions
29
docker-compose.yml
Normal file
29
docker-compose.yml
Normal file
|
|
@ -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:
|
||||
9
web/.env.example
Normal file
9
web/.env.example
Normal file
|
|
@ -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=
|
||||
14
web/Dockerfile
Normal file
14
web/Dockerfile
Normal file
|
|
@ -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"]
|
||||
|
|
@ -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()
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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)
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue