> For the complete documentation index, see [llms.txt](https://close.gitbook.io/yun-wei-bi-ji/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://close.gitbook.io/yun-wei-bi-ji/python/fastapi/fastapi-zhong-jian-jian.md).

# FastAPI 中间件

> "中间件"是一个函数,它在每个请求被特定的路径操作处理之前,以及在每个响应返回之前工作.

```python
import time
from fastapi import FastAPI, Request
app = FastAPI()

# 使用中间在返回的数据中头部添加一些东西
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
    start_time = time.time()
    response = await call_next(request)
    process_time = time.time() - start_time
    response.headers["X-Process-Time"] = str(process_time)
    response.headers['leizishuocceshikaifa']="leizishuoceshikaifa"
    return response

@app.post("/create")
def post():
    return "post"
```
