簡體   English   中英

如何從中間件設置屬性以在 FastAPI 中請求對象?

[英]How can I set attribute to request object in FastAPI from middleware?

如何從中間件函數為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}

此設置引發異常,

AttributeError: 'Request' 對象沒有屬性 'custom_attr'

那么,如何在路由器中獲取"This is my custom attribute"值?

我們無法為request對象附加/設置屬性(如果我錯了, 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`

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM