Files
xiaoxia-saas/apps/api/main.py
T
Xiaoxia AI 4495d0c53d
Deploy / Deploy Staging (push) Failing after 6s
Deploy / Deploy Production (push) Has been skipped
Tests / test (push) Failing after 30s
Tests / lint (push) Failing after 27s
feat(middleware): add comprehensive error handling and logging
- Add APIException with custom error codes
- Implement global exception handlers (API/HTTP/Validation/General)
- Add RequestLoggingMiddleware with response time tracking
- Add RateLimitMiddleware (in-memory rate limiting)
- Integrate all middleware into main app
- Return consistent JSON error responses
- Add X-Process-Time and X-RateLimit headers

Phase 4 Task 33/68 completed
2026-06-17 08:14:47 +08:00

87 lines
2.2 KiB
Python

"""
FastAPI 主应用
"""
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.gzip import GZipMiddleware
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from apps.api.app.api.routes import api_router
from apps.api.app.middleware.exceptions import (
APIException,
api_exception_handler,
http_exception_handler,
validation_exception_handler,
general_exception_handler,
)
from apps.api.app.middleware.logging import (
RequestLoggingMiddleware,
RateLimitMiddleware,
)
# 创建 FastAPI 应用
app = FastAPI(
title="小虾 SaaS API",
description="自动化剪辑 SaaS 平台 API",
version="1.0.0",
docs_url="/docs",
redoc_url="/redoc",
)
# 注册异常处理器
app.add_exception_handler(APIException, api_exception_handler)
app.add_exception_handler(StarletteHTTPException, http_exception_handler)
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(Exception, general_exception_handler)
# CORS 中间件
app.add_middleware(
CORSMiddleware,
allow_origins=[
"http://localhost:3000",
"http://localhost:5173",
"https://yourdomain.com",
],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
# Gzip 压缩
app.add_middleware(GZipMiddleware, minimum_size=1000)
# 请求日志
app.add_middleware(RequestLoggingMiddleware)
# 速率限制(开发环境关闭,生产环境启用)
# app.add_middleware(RateLimitMiddleware, max_requests=100, window_seconds=60)
# 注册路由
app.include_router(api_router)
@app.get("/")
async def root():
"""健康检查"""
return {
"service": "小虾 SaaS API",
"status": "running",
"version": "1.0.0",
}
@app.get("/health")
async def health_check():
"""健康检查接口"""
return {
"status": "healthy",
"database": "ok", # TODO: 实际检查数据库连接
"redis": "ok", # TODO: 实际检查 Redis 连接
}
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000)