8fe8047429
- 路由:GET/POST/PUT/DELETE /api/v1/companies - 支持分页、关键词搜索、行业/阶段筛选 - 租户隔离:只能操作本租户企业 - 测试:11 个企业 CRUD 测试,全部 passed(总计 26 tests)
72 lines
1.8 KiB
Python
72 lines
1.8 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.routers.companies import router as companies_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")
|
|
app.include_router(companies_router, prefix="/api/v1")
|