79 lines
2.3 KiB
Python
79 lines
2.3 KiB
Python
"""FastAPI application setup and configuration."""
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
from starlette.middleware.base import BaseHTTPMiddleware
|
|
|
|
from privatestudio.web.database import upgrade_db
|
|
from privatestudio.web.routes import assets, transcode, profiles, keys, userinfo, s3_keys
|
|
|
|
|
|
class CacheBodyMiddleware(BaseHTTPMiddleware):
|
|
"""Middleware to cache request body for multiple reads."""
|
|
|
|
async def dispatch(self, request, call_next):
|
|
body = await request.body()
|
|
request.state._body = body
|
|
|
|
async def receive():
|
|
return {"type": "http.request", "body": body, "more_body": False}
|
|
|
|
request._receive = receive
|
|
response = await call_next(request)
|
|
return response
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""Lifespan context manager to initialize the database on startup."""
|
|
upgrade_db()
|
|
yield
|
|
|
|
# Create FastAPI app
|
|
app = FastAPI(
|
|
title="Private Studio",
|
|
description="Video transcoding web service with S3-compatible interface",
|
|
version="0.1.0",
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
# Add middleware to cache request body (must be before CORS)
|
|
app.add_middleware(CacheBodyMiddleware)
|
|
|
|
# Add CORS middleware
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["*"], # Configure in production
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
@app.get("/health")
|
|
async def health_check():
|
|
"""Health check endpoint."""
|
|
return {"status": "ok"}
|
|
|
|
|
|
# Include routes
|
|
app.include_router(keys.router, prefix="/api", tags=["Keys"])
|
|
app.include_router(s3_keys.router, prefix="/api", tags=["S3 Keys"])
|
|
app.include_router(assets.router, prefix="/s3", tags=["S3"])
|
|
app.include_router(transcode.router, prefix="/api", tags=["Transcode"])
|
|
app.include_router(profiles.router, prefix="/api", tags=["Profiles"])
|
|
app.include_router(userinfo.router, prefix="/api", tags=["UserInfo"])
|
|
|
|
|
|
@app.exception_handler(ValueError)
|
|
async def value_error_handler(request, exc):
|
|
"""Handle ValueError exceptions."""
|
|
return JSONResponse(status_code=400, content={"detail": str(exc)})
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import uvicorn
|
|
uvicorn.run(app, host="0.0.0.0", port=8000)
|