ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

FastAPI从入门到实战(18)——FastAPI 中间件、CORS、后台任务

2026/9/24 14:17:35 拓冰建站 浏览量
FastAPI从入门到实战(18)——FastAPI 中间件、CORS、后台任务

中间件

@app.middleware('http')
async def add_process_time_header(request: Request, call_next):  # call_next将接收request请求做为参数start_time = time.time()response = await call_next(request)process_time = time.time() - start_timeresponse.headers['X-Process-Time'] = str(process_time)  # 添加自定义的以“X-”开头的请求头return response

带yield的依赖的退出部分的代码 和 后台任务 会在中间件之后运行

CORS

from fastapi.middleware.cors import CORSMiddlewareapp.add_middleware(CORSMiddleware,allow_origins=["http://127.0.0.1","http://127.0.0.1:8000"],allow_credentials=True,allow_methods=["*"],allow_headers=["*"],
)

后台任务

from fastapi import BackgroundTasksdef bg_task(framework: str):with open("README.md", mode="a") as f:f.write(f"## {framework} 框架精讲")@app08.post("/background_tasks")
async def run_bg_task(framework: str, background_tasks: BackgroundTasks):""":param framework: 被调用的后台任务函数的参数:param background_tasks: FastAPI.BackgroundTasks:return:"""background_tasks.add_task(bg_task, framework)return {"message": "任务已在后台运行"}