2be0778ec7
- 后端:auth 路由(register/login/refresh/me)+ JWT + bcrypt 密码哈希 - 依赖注入:get_current_user + require_role 角色权限校验 - 跨数据库兼容:JSONBType(PG 用 JSONB,SQLite 用 JSON) - 测试:11 个认证测试 + 4 个健康检查测试 = 15 passed
70 lines
1.7 KiB
Python
70 lines
1.7 KiB
Python
"""FastAPI 应用入口。
|
|
|
|
注册中间件、路由、异常处理。
|
|
"""
|
|
|
|
import uuid
|
|
from contextlib import asynccontextmanager
|
|
|
|
from fastapi import FastAPI, Request
|
|
from fastapi.middleware.cors import CORSMiddleware
|
|
from fastapi.responses import JSONResponse
|
|
|
|
from app.routers.auth import router as auth_router
|
|
from app.schemas.common import error
|
|
|
|
|
|
@asynccontextmanager
|
|
async def lifespan(app: FastAPI):
|
|
"""应用生命周期管理。"""
|
|
# startup
|
|
yield
|
|
# shutdown
|
|
|
|
|
|
app = FastAPI(
|
|
title="AIPortPilot",
|
|
description="AI+ Portfolio Operating System — 投后管理与组合协同平台",
|
|
version="0.1.0",
|
|
lifespan=lifespan,
|
|
)
|
|
|
|
# CORS
|
|
app.add_middleware(
|
|
CORSMiddleware,
|
|
allow_origins=["http://localhost:3000"],
|
|
allow_credentials=True,
|
|
allow_methods=["*"],
|
|
allow_headers=["*"],
|
|
)
|
|
|
|
|
|
@app.middleware("http")
|
|
async def trace_id_middleware(request: Request, call_next):
|
|
"""为每个请求注入 trace_id。"""
|
|
trace_id = request.headers.get("X-Trace-Id", str(uuid.uuid4()))
|
|
request.state.trace_id = trace_id
|
|
response = await call_next(request)
|
|
response.headers["X-Trace-Id"] = trace_id
|
|
return response
|
|
|
|
|
|
@app.exception_handler(Exception)
|
|
async def global_exception_handler(request: Request, exc: Exception):
|
|
"""全局异常处理。"""
|
|
trace_id = getattr(request.state, "trace_id", str(uuid.uuid4()))
|
|
return JSONResponse(
|
|
status_code=500,
|
|
content=error(code=-1, message="内部服务器错误"),
|
|
headers={"X-Trace-Id": trace_id},
|
|
)
|
|
|
|
|
|
@app.get("/health")
|
|
async def health_check():
|
|
"""健康检查端点。"""
|
|
return {"status": "ok", "service": "aiportpilot-backend", "version": "0.1.0"}
|
|
|
|
|
|
app.include_router(auth_router, prefix="/api/v1")
|