0

我有一个看起来像这样的函数:

@app.middleware("http")
async def process_api_event(request: Request, call_next):
     url = request.url
     path = request.url.path 
     # request.__setattr__('url', 'sample_url')
     # request.url.__ setattr__('path', 'sample_path')

在上面的函数中,我想根据情况改变请求的url,或者路径。我试过了request.__setattr__('url', 'sample_url')request.url.__ setattr__('path', 'sample_path')如上所示,但由于AttributeError: can't set attribute error. 我通读了 FastAPI 和 Starlette 文档,但在这种情况下找不到我需要的信息。任何帮助将不胜感激!

4

1 回答 1

0

request.url是一个获取属性的属性,_url所以你可以设置_url(但不会改变)request.scoperequest.base_url

from starlette.datastructures import URL

@app.middleware("http")
async def process_api_event(request: Request, call_next):
    request._url = URL('sample_url')
    print(request.url)
    ...
于 2020-10-30T08:35:27.197 回答