-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathmain.py
More file actions
31 lines (23 loc) · 997 Bytes
/
Copy pathmain.py
File metadata and controls
31 lines (23 loc) · 997 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
"""
FastAPI 应用入口
负责创建后端应用实例,注册应用生命周期函数,并把各业务模块中的 router
挂载到同一个 app 上。HTTP 请求会先进入这里创建的 app,再按路由分发到
具体的接口处理函数。
"""
import uuid
from fastapi import FastAPI, Request
from app.api.lifespan import lifespan
from app.api.routers.query_router import query_router
from app.core.context import request_id_ctx_var
# lifespan 交给 FastAPI 管理,用于在服务启动和关闭时统一初始化与释放外部客户端
app = FastAPI(lifespan=lifespan)
# 把查询路由注册进应用;没有挂载时,/docs 和真实 HTTP 请求都访问不到该接口
app.include_router(query_router)
@app.middleware("http")
async def add_request_id(request: Request, call_next):
# 请求被处理之前
request_id = uuid.uuid4()
request_id_ctx_var.set(request_id)
response = await call_next(request)
# 请求被处理之后
return response