如何从中间件将属性设置为FastAPI中的请求对象



如何从中间件函数为Request对象设置任意属性?

from fastapi import FastAPI, Request
app = FastAPI()

@app.middleware("http")
async def set_custom_attr(request: Request, call_next):
request.custom_attr = "This is my custom attribute"
response = await call_next(request)
return response

@app.get("/")
async def root(request: Request):
return {"custom_attr": request.custom_attr}

此设置引发了一个异常

属性错误:"请求"对象没有属性"custom_attr"

那么,如何在路由器中获得"This is my custom attribute"

我们无法将属性附加/设置到request对象(如果我错了,请纠正我(。

但是,我们可以使用Request.state--(Doc(属性

from fastapi import FastAPI, Request
app = FastAPI()

@app.middleware("http")
async def set_custom_attr(request: Request, call_next):
request.state.custom_attr = "This is my custom attribute" # setting the value to `request.state`
response = await call_next(request)
return response

@app.get("/")
async def root(request: Request):
return {"custom_attr":request.state.custom_attr} # accessing the value from `request.state`

最新更新