| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364 |
- from fastapi import FastAPI, Depends
- from fastapi.middleware.cors import CORSMiddleware
- from fastapi.openapi.utils import get_openapi
- from fastapi.security import HTTPBearer
- from app.api import router
- from app.core.auth import verify_token
- from app.core.config import settings
- app = FastAPI(title=settings.app_name)
- # -----------------------
- # CORS(可选)
- # -----------------------
- app.add_middleware(
- CORSMiddleware,
- allow_origins=["*"],
- allow_methods=["*"],
- allow_headers=["*"],
- )
- # -----------------------
- # 路由注册
- # -----------------------
- # 公共路由,不鉴权
- app.include_router(
- router.public_router,
- prefix="/api"
- )
- # 需要鉴权的路由
- app.include_router(
- router.protected_router,
- prefix="/api",
- #dependencies=[Depends(verify_token)]
- )
- # -----------------------
- # Swagger 支持 Bearer Token
- # -----------------------
- def custom_openapi():
- if app.openapi_schema:
- return app.openapi_schema
- openapi_schema = get_openapi(
- title=app.title,
- version="1.0.0",
- description="API documentation",
- routes=app.routes,
- )
- # 添加全局 Bearer
- openapi_schema["components"]["securitySchemes"] = {
- "BearerAuth": {
- "type": "http",
- "scheme": "bearer",
- "bearerFormat": "JWT"
- }
- }
- for path in openapi_schema["paths"].values():
- for method in path.values():
- method["security"] = [{"BearerAuth": []}]
- app.openapi_schema = openapi_schema
- return app.openapi_schema
- app.openapi = custom_openapi
|