0

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!

lovprogramming
  • 593
  • 11
  • 24

1 Answers1

0

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)
    ...
r-m-n
  • 14,192
  • 4
  • 69
  • 68