Fastapi: How to set global variable in request lifecycle?

Created on 21 Oct 2019  路  8Comments  路  Source: tiangolo/fastapi

How can I set some data in global request lifecycle which can be used throughout the app
In flask, it was possible via,

from flask import g
g.data  = {}

tried setting data to the incoming requests, but it turns out request is read-only. Please help!
Thanks in advance.

question

Most helpful comment

Hi @knowBalpreet and other contributors of this issue.

I just learned the new contextvars that comes with Python 3.7+, and made this Gist that provide a request lifecycle pseudo-global similar to the Flask "g" object.

https://gist.github.com/glenfant/2fe530e5a2b90c28608165b5a18afcaf

Any comment on the Gist is welcome.

All 8 comments

You can get/set arbitrary attributes on request.state

You can get/set arbitrary attributes on request.state

Thanks for the suggestion. I was able to set data there and fetch in the endpoint as well. How do I access this global data when I don't have the request, for example how do you access request state in a dependency?

Please consider the following use case:

class Verify_Permissions:
  def __init__(self, permissions: List[Dict]):
    self.permissions = permissions

  def __call__(self):
    success, message = validate_permissions(self.permissions)
    if not success:
      raise HTTPException(
          status_code=HTTP_401_UNAUTHORIZED, detail=message)

@router.post('/user', tags=['Account'], dependencies=[
    Depends(Verify_Permissions(
        [{
            "resource": "users",
            "actions": ["CAN_ADD"],
            "consumption": True
        }]
    ))])
async def add_user(request: Request, data: AccountModel):
  """
    Add user to an account in the platform
  """
  global_data = request.state.__dict__.get('_state', {})
  return services.add_user(data.dict(), global_data)

The validate permission needs userId which is in global_data which was set in the middleware.

If there is any other way to do this, please suggest

You can access the request in a dependency the same way you would in an endpoint. Just add it as a parameter to the dependency.

As @dmontagu says :point_up:

Here are the docs for that: https://fastapi.tiangolo.com/tutorial/using-request-directly/

Assuming the original issue was solved, it will be automatically closed now. But feel free to add more comments or create new issues.

https://fastapi.tiangolo.com/tutorial/using-request-directly/ is a broken link. Can someone kindly point me to the updated location? 馃檹

Hi @knowBalpreet and other contributors of this issue.

I just learned the new contextvars that comes with Python 3.7+, and made this Gist that provide a request lifecycle pseudo-global similar to the Flask "g" object.

https://gist.github.com/glenfant/2fe530e5a2b90c28608165b5a18afcaf

Any comment on the Gist is welcome.

Was this page helpful?
0 / 5 - 0 ratings