简体   繁体   中英

FastAPI - Set the url or path for the Request object

I have a function that looks like this:

@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')

In the above function, depending on the situation I would like to change the request url, or path. I tried request.__setattr__('url', 'sample_url') and request.url.__ setattr__('path', 'sample_path') as shown above but I wasn't able to do it due to AttributeError: can't set attribute error . I read through the FastAPI and Starlette documentation, but couldn't really find info that I needed in this case. Any help would be greatly appreciated!

request.url is a property that gets _url attribute, so you can set _url (but request.scope and request.base_url will not change)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM