104 lines
2.5 KiB
Python
104 lines
2.5 KiB
Python
"""
|
|
应用工厂模式 - 创建和配置 FastAPI 应用实例
|
|
"""
|
|
from fastapi import FastAPI
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from app.core.config import settings
|
|
|
|
|
|
def create_application() -> FastAPI:
|
|
"""
|
|
创建 FastAPI 应用实例
|
|
|
|
Returns:
|
|
FastAPI: 配置完成的应用实例
|
|
"""
|
|
app = FastAPI(
|
|
title=settings.PROJECT_NAME,
|
|
version=settings.VERSION,
|
|
description=settings.DESCRIPTION,
|
|
debug=settings.DEBUG,
|
|
docs_url=settings.DOCS_URL,
|
|
redoc_url=settings.REDOC_URL
|
|
)
|
|
|
|
# 设置中间件
|
|
setup_middleware(app)
|
|
|
|
# 注册路由
|
|
register_routers(app)
|
|
|
|
# 注册事件处理器
|
|
register_events(app)
|
|
|
|
return app
|
|
|
|
|
|
def setup_middleware(app: FastAPI) -> None:
|
|
"""
|
|
配置应用中间件
|
|
|
|
Args:
|
|
app: FastAPI 应用实例
|
|
"""
|
|
# CORS 中间件配置
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=settings.CORS_ORIGINS,
|
|
allow_credentials=settings.CORS_ALLOW_CREDENTIALS,
|
|
allow_methods=settings.CORS_ALLOW_METHODS,
|
|
allow_headers=settings.CORS_ALLOW_HEADERS,
|
|
)
|
|
|
|
# 可以在这里添加其他中间件
|
|
# app.add_middleware(...)
|
|
|
|
|
|
def register_routers(app: FastAPI) -> None:
|
|
"""
|
|
注册所有路由
|
|
|
|
Args:
|
|
app: FastAPI 应用实例
|
|
"""
|
|
from app.api.v1.router import api_router
|
|
|
|
# 注册 API v1 路由
|
|
app.include_router(api_router, prefix="/api/v1")
|
|
|
|
# 根路径路由
|
|
@app.get("/")
|
|
async def root():
|
|
return {
|
|
"message": "Welcome to FastAPI Demo",
|
|
"version": settings.VERSION,
|
|
"docs": "/docs",
|
|
"redoc": "/redoc"
|
|
}
|
|
|
|
# 健康检查路由
|
|
@app.get("/health")
|
|
async def health_check():
|
|
return {"status": "healthy", "service": settings.PROJECT_NAME}
|
|
|
|
|
|
def register_events(app: FastAPI) -> None:
|
|
"""
|
|
注册应用事件处理器
|
|
|
|
Args:
|
|
app: FastAPI 应用实例
|
|
"""
|
|
@app.on_event("startup")
|
|
async def startup_event():
|
|
"""应用启动时执行"""
|
|
print(f"[INFO] {settings.PROJECT_NAME} v{settings.VERSION} is starting up...")
|
|
# 可以在这里添加启动时的初始化操作
|
|
# 如:数据库连接、缓存初始化等
|
|
|
|
@app.on_event("shutdown")
|
|
async def shutdown_event():
|
|
"""应用关闭时执行"""
|
|
print(f"[INFO] {settings.PROJECT_NAME} is shutting down...")
|
|
# 可以在这里添加关闭时的清理操作
|
|
# 如:关闭数据库连接、保存缓存等 |