Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/356.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从中间件将属性设置为FastAPI中的请求对象?_Python_Middleware_Fastapi - Fatal编程技术网

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

Python 如何从中间件将属性设置为FastAPI中的请求对象?,python,middleware,fastapi,Python,Middleware,Fastapi,如何从中间件函数为请求对象设置任意属性 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 = awa

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

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}
此安装程序引发异常

AttributeError:“请求”对象没有“自定义属性”


因此,如何在我的路由器中获取
“这是我的自定义属性”
值?

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

但是,我们可以利用这个属性

从fastapi导入fastapi,请求
app=FastAPI()
@应用程序中间件(“http”)
异步定义设置\自定义\属性(请求:请求,调用\下一步):
request.state.custom_attr=“这是我的自定义属性”#将值设置为'request.state'`
响应=等待呼叫\u下一步(请求)
返回响应
@app.get(“/”)
异步定义根目录(请求:请求):

返回{“custom_attr”:request.state.custom_attr}#从'request.state`
访问值。好的,您正在将它附加到请求对象:更准确地说,这是Starlete的一个特点:
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`