141 lines
4.0 KiB
Python
141 lines
4.0 KiB
Python
# app/main.py
|
|
import logging
|
|
import uvicorn
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from starlette.middleware.sessions import SessionMiddleware
|
|
import sentry_sdk
|
|
from sentry_sdk.integrations.fastapi import FastApiIntegration
|
|
|
|
from app.api.api_router import api_router
|
|
from app.config import settings
|
|
from app.core.api_config import API_METADATA, API_TAGS
|
|
from app.auth import fastapi_users, auth_backend
|
|
from app.models import User
|
|
from app.api.auth.oauth import router as oauth_router
|
|
|
|
# Initialize Sentry
|
|
sentry_sdk.init(
|
|
dsn=settings.SENTRY_DSN,
|
|
integrations=[
|
|
FastApiIntegration(),
|
|
],
|
|
# Set traces_sample_rate to 1.0 to capture 100% of transactions for performance monitoring.
|
|
# We recommend adjusting this value in production.
|
|
traces_sample_rate=1.0,
|
|
# If you wish to associate users to errors (assuming you are using
|
|
# FastAPI's users system) you may enable sending PII data.
|
|
send_default_pii=True
|
|
)
|
|
|
|
# --- Logging Setup ---
|
|
logging.basicConfig(
|
|
level=getattr(logging, settings.LOG_LEVEL),
|
|
format=settings.LOG_FORMAT
|
|
)
|
|
logger = logging.getLogger(__name__)
|
|
|
|
# --- FastAPI App Instance ---
|
|
app = FastAPI(
|
|
**API_METADATA,
|
|
openapi_tags=API_TAGS
|
|
)
|
|
|
|
# Add session middleware for OAuth
|
|
app.add_middleware(
|
|
SessionMiddleware,
|
|
secret_key=settings.SESSION_SECRET_KEY
|
|
)
|
|
|
|
# --- CORS Middleware ---
|
|
# Define allowed origins. Be specific in production!
|
|
# Use ["*"] for wide open access during early development if needed,
|
|
# but restrict it as soon as possible.
|
|
# SvelteKit default dev port is 5173
|
|
origins = [
|
|
"http://localhost:5174",
|
|
"http://localhost:8000", # Allow requests from the API itself (e.g., Swagger UI)
|
|
# Add your deployed frontend URL here later
|
|
# "https://your-frontend-domain.com",
|
|
]
|
|
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.CORS_ORIGINS,
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
# --- End CORS Middleware ---
|
|
|
|
|
|
# --- Include API Routers ---
|
|
# Include FastAPI-Users routes
|
|
app.include_router(
|
|
fastapi_users.get_auth_router(auth_backend),
|
|
prefix="/auth/jwt",
|
|
tags=["auth"],
|
|
)
|
|
app.include_router(
|
|
fastapi_users.get_register_router(),
|
|
prefix="/auth",
|
|
tags=["auth"],
|
|
)
|
|
app.include_router(
|
|
fastapi_users.get_reset_password_router(),
|
|
prefix="/auth",
|
|
tags=["auth"],
|
|
)
|
|
app.include_router(
|
|
fastapi_users.get_verify_router(),
|
|
prefix="/auth",
|
|
tags=["auth"],
|
|
)
|
|
app.include_router(
|
|
fastapi_users.get_users_router(),
|
|
prefix="/users",
|
|
tags=["users"],
|
|
)
|
|
|
|
# Include OAuth routes
|
|
app.include_router(oauth_router, prefix="/auth", tags=["auth"])
|
|
|
|
# Include your API router
|
|
app.include_router(api_router, prefix=settings.API_PREFIX)
|
|
# --- End Include API Routers ---
|
|
|
|
|
|
# --- Root Endpoint (Optional - outside the main API structure) ---
|
|
@app.get("/", tags=["Root"])
|
|
async def read_root():
|
|
"""
|
|
Provides a simple welcome message at the root path.
|
|
Useful for basic reachability checks.
|
|
"""
|
|
logger.info("Root endpoint '/' accessed.")
|
|
return {"message": settings.ROOT_MESSAGE}
|
|
# --- End Root Endpoint ---
|
|
|
|
|
|
# --- Application Startup/Shutdown Events (Optional) ---
|
|
@app.on_event("startup")
|
|
async def startup_event():
|
|
logger.info("Application startup: Connecting to database...")
|
|
# You might perform initial checks or warm-up here
|
|
# await database.engine.connect() # Example check (get_db handles sessions per request)
|
|
logger.info("Application startup complete.")
|
|
|
|
@app.on_event("shutdown")
|
|
async def shutdown_event():
|
|
logger.info("Application shutdown: Disconnecting from database...")
|
|
# await database.engine.dispose() # Close connection pool
|
|
logger.info("Application shutdown complete.")
|
|
# --- End Events ---
|
|
|
|
|
|
# --- Direct Run (for simple local testing if needed) ---
|
|
# It's better to use `uvicorn app.main:app --reload` from the terminal
|
|
# if __name__ == "__main__":
|
|
# logger.info("Starting Uvicorn server directly from main.py")
|
|
# uvicorn.run(app, host="0.0.0.0", port=8000)
|
|
# ------------------------------------------------------ |