I want to access a global variable when a fastAPI is hit, and at the end of API i want to update that global variable.
Have you looked into middlewares? https://fastapi.tiangolo.com/tutorial/middleware/
yes but does this maintain the state?
say i want to increment a counter everytime a request is hit ,
how can i do that?
lets say i want to update below dictionary for every request , and also maintain the state of the dictionary:-
for ex:-
{"counter": 0, "yawnStatus": "False", "yawnCount": 0, "prevYawnStatus": "False"}
for each request, i want to update this counter and update other variables in dictionary so that in next request i can use them.
You could store it in the app.state attribute?
So
request.app.state.whatever = {"counter": 0}

I did this, but counter is not incrementing,
it is printing 1 everytime for each request, however should goes like:- 1,2,3,4,......
Try something like
app.state = 0
def wellness(request: Request):
request.app.state.counter += 1

It worked , thanks a lot..!!!!! (y)
Feel free to close the issue :)
Most helpful comment
Try something like