FastAPI - 为 Request 对象设置 url 或路径

FastAPI - Set the url or path for the Request object

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

@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 文档,但在这种情况下找不到我需要的信息。任何帮助将不胜感激!

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)
    ...