Fix aiomysql pool_pre_ping crash, add rate limiting and security hardening
Remove pool_pre_ping=True to fix startup crash caused by aiomysql 0.2.0 async adapter requiring a reconnect argument SQLAlchemy does not pass. Add slowapi rate limiting, structured logging, CORS config, backend health check, and nginx security headers. Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
+21
-1
@@ -1,13 +1,23 @@
|
||||
import logging
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy import select
|
||||
from slowapi import _rate_limit_exceeded_handler
|
||||
from slowapi.errors import RateLimitExceeded
|
||||
|
||||
from app.config import settings
|
||||
from app.database import init_db, AsyncSessionLocal
|
||||
from app.limiter import limiter
|
||||
from app.routers import auth, users, entries, public, admin
|
||||
|
||||
logging.basicConfig(
|
||||
level=logging.INFO,
|
||||
format="%(asctime)s %(levelname)s %(name)s %(message)s",
|
||||
)
|
||||
logger = logging.getLogger("bourbonacci")
|
||||
|
||||
|
||||
async def _seed_admin() -> None:
|
||||
from app.models.user import User
|
||||
@@ -33,14 +43,19 @@ async def _seed_admin() -> None:
|
||||
async def lifespan(app: FastAPI):
|
||||
await init_db()
|
||||
await _seed_admin()
|
||||
logger.info("Bourbonacci started")
|
||||
yield
|
||||
logger.info("Bourbonacci shutting down")
|
||||
|
||||
|
||||
app = FastAPI(title="Bourbonacci", lifespan=lifespan)
|
||||
|
||||
app.state.limiter = limiter
|
||||
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_origins=[o.strip() for o in settings.allowed_origins.split(",")],
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
@@ -50,3 +65,8 @@ app.include_router(users.router)
|
||||
app.include_router(entries.router)
|
||||
app.include_router(public.router)
|
||||
app.include_router(admin.router)
|
||||
|
||||
|
||||
@app.get("/health")
|
||||
async def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
Reference in New Issue
Block a user