I want to access request object inside the files other than routes, how to use this.
i.e. how to access the request globals similar to g and current_app in flask.
Reference: https://flask.palletsprojects.com/en/1.0.x/api/#flask.g
You can store your data in the application variable and access the application from the request directly:
app = FastAPI()
app.some_var = 'test'
....
from fastapi import Request
@app.get('/')
async def get_something(request: Request):
logging.debug(request.app.some_var)
I think a more proper place to store those is in app.state.
Thanks for the help here everyone! :clap: :bow:
@ankithherle a request is not really a global object, Flask does some tricks with thread locals and proxy objects to make it look like that. And thread locals are a tool that only works with simple threaded applications, it doesn't work in async contexts. In those cases (and all the cases in modern Python) you need instead context vars.
But if you need to access the request in other functions, the safest and best thing you could do is pass it in the function arguments and access it directly.
If you absolutely, totally need to access the request as a request-specific "global" from other functions with the same black-magic style, for some very specific reason, you could put the request in a contextvar variable in a middleware and then access it from your functions as a contextvar. That would require Python 3.7. Or you could use something like https://github.com/tomwojcik/starlette-context
But again, if you can handle it more explicitly without all that, that would make your life/code a lot simpler.
Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.
Most helpful comment
Thanks for the help here everyone! :clap: :bow:
@ankithherle a request is not really a global object, Flask does some tricks with thread locals and proxy objects to make it look like that. And thread locals are a tool that only works with simple threaded applications, it doesn't work in async contexts. In those cases (and all the cases in modern Python) you need instead context vars.
But if you need to access the request in other functions, the safest and best thing you could do is pass it in the function arguments and access it directly.
If you absolutely, totally need to access the request as a request-specific "global" from other functions with the same black-magic style, for some very specific reason, you could put the request in a contextvar variable in a middleware and then access it from your functions as a contextvar. That would require Python 3.7. Or you could use something like https://github.com/tomwojcik/starlette-context
But again, if you can handle it more explicitly without all that, that would make your life/code a lot simpler.