Same routes, same Docker topology, same env vars. Frontend untouched.
Backend swap:
- Hono on Node -> FastAPI on Python 3.12, served by uvicorn behind Caddy.
- Drizzle on Node -> SQLAlchemy 2.0 async (asyncpg driver) with declarative
models that mirror the previous schema 1:1. Migrations are still plain
SQL files (apps/api/app/migrations/) run idempotently at startup by
app/db/migrate.py via asyncpg, tracking each file's sha256 in a
schema_migrations table.
- aws4fetch -> boto3 wrapped in asyncio.to_thread so the async routes
do not block on MinIO/S3 calls. The presign_put / init_multipart /
complete_multipart / head / delete contract is unchanged so the React
client sees the same /api/uploads/* payloads.
- Cookie+JWT admin auth -> pyjwt + FastAPI Cookie() dependency.
constant-time password compare. Same 7-day HttpOnly cookie shape.
- QR code: qrcode lib + reportlab. /api/qrcode keeps format=png|svg|pdf;
the PDF is still A6 with the couple's names + 'Aponte a câmera' CTA.
- Pydantic-settings replaces the zod env loader and still fails fast
on missing required vars.
Routes ported with identical paths and JSON shapes:
- public: /api/event, /api/gallery, /api/qrcode, /api/stats
- uploads: /api/uploads/init, /{id}/confirm, /{id}/abort
- admin: /login, /logout, /me, /event (GET+PATCH), /uploads (GET with
?status, ?kind=photo|video, ?q= for search), /uploads/{id} (PATCH
for author/message edit), /uploads/{id}/{approve,reject,cover},
/uploads/{id} (DELETE), /event/cover (DELETE), /uploads/bulk, /stats.
Build pipeline:
- Dockerfile: stage 1 builds the React/Vite SPA with pnpm; stage 2 is
python:3.12-slim that installs deps via uv (fast, reproducible),
copies the app/, and copies the SPA dist from stage 1 into /app/public
so the FastAPI process serves both /api/* and the SPA assets.
- docker-compose.yml unchanged: postgres + minio + minio-init + app +
caddy. Same env vars (DATABASE_URL, S3_*, ADMIN_PASSWORD, SESSION_SECRET,
ALLOWED_ADMIN_EMAILS, AUTO_MIGRATE).
- Removed apps/api from the pnpm workspace; root package.json now only
scripts the web. Makefile centralizes dev/build/docker commands so
the Python side has the same DX as the Node side did.
71 lines
2.0 KiB
Python
71 lines
2.0 KiB
Python
import asyncio
|
|
import hashlib
|
|
from pathlib import Path
|
|
|
|
import asyncpg
|
|
|
|
|
|
def _to_pg_url(url: str) -> str:
|
|
if url.startswith("postgres://"):
|
|
url = "postgresql://" + url[len("postgres://") :]
|
|
if url.startswith("postgresql+asyncpg://"):
|
|
url = "postgresql://" + url[len("postgresql+asyncpg://") :]
|
|
return url
|
|
|
|
|
|
async def run_migrations(database_url: str) -> None:
|
|
conn = await asyncpg.connect(_to_pg_url(database_url))
|
|
try:
|
|
await conn.execute(
|
|
"""
|
|
CREATE TABLE IF NOT EXISTS schema_migrations (
|
|
name TEXT PRIMARY KEY,
|
|
sha256 TEXT NOT NULL,
|
|
applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW()
|
|
)
|
|
"""
|
|
)
|
|
|
|
migrations_dir = Path(__file__).parent.parent / "migrations"
|
|
files = sorted(f for f in migrations_dir.iterdir() if f.suffix == ".sql")
|
|
|
|
for f in files:
|
|
content = f.read_text(encoding="utf-8")
|
|
sha = hashlib.sha256(content.encode("utf-8")).hexdigest()
|
|
|
|
existing = await conn.fetchrow(
|
|
"SELECT sha256 FROM schema_migrations WHERE name = $1", f.name
|
|
)
|
|
|
|
if existing is not None:
|
|
if existing["sha256"] != sha:
|
|
raise RuntimeError(
|
|
f"Migration {f.name} has been modified after being applied. "
|
|
"Add a new migration file instead."
|
|
)
|
|
print(f"[migrate] skip {f.name}")
|
|
continue
|
|
|
|
print(f"[migrate] apply {f.name}")
|
|
async with conn.transaction():
|
|
await conn.execute(content)
|
|
await conn.execute(
|
|
"INSERT INTO schema_migrations (name, sha256) VALUES ($1, $2)",
|
|
f.name,
|
|
sha,
|
|
)
|
|
|
|
print("[migrate] done")
|
|
finally:
|
|
await conn.close()
|
|
|
|
|
|
def main() -> None:
|
|
from ..config import settings
|
|
|
|
asyncio.run(run_migrations(settings.DATABASE_URL))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|