Global variable is not updated inside @get decorator #8355
Replies: 8 comments
-
Not sure if this is a FastAPI issue. |
Beta Was this translation helpful? Give feedback.
-
Agreed with @iudeen , this code is not reproducible. Please provide a reproducible example so we can help you. Below is a working example using a global variable: from fastapi import Body, FastAPI
app = FastAPI()
data1 = {}
@app.post("/update")
def update_data1(text1: str = Body(), text2: str = Body()):
global data1
data1["text1"] = text1
data1["text2"] = text2
return data1
@app.get("/get")
async def get_data1():
global data1
return data1
if __name__ == "__main__":
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8000) Changing the global variable through a POST: curl -X 'POST' \
'http://0.0.0.0:8000/update' \
-H 'accept: application/json' \
-H 'Content-Type: application/json' \
-d '{
"text1": "this is text1",
"text2": "this is text2"
}'
>>>
{
"text1": "this is text1",
"text2": "this is text2"
} Getting the newly updated global variable through the GET endpoint: curl -X 'GET' \
'http://0.0.0.0:8000/get' \
-H 'accept: application/json'
>>>
{
"text1": "this is text1",
"text2": "this is text2"
} |
Beta Was this translation helpful? Give feedback.
-
thanks for the reply, but that is not what im achieving to do. |
Beta Was this translation helpful? Give feedback.
-
You want to return a global variable in your endpoint, no? And this global variable is set from another function? I am only demonstrating that this is perfectly possible, but you didn't provide a reproducible example, so I made my own. |
Beta Was this translation helpful? Give feedback.
-
I have edited the code. To run the code you need to run a server rabbitmq. |
Beta Was this translation helpful? Give feedback.
-
From your code, I don't see a line that starts FastAPI server. How are you starting it? If you're starting it outside like using |
Beta Was this translation helpful? Give feedback.
-
Thanks for the hint. I solved my problem following the issue on this link #543 |
Beta Was this translation helpful? Give feedback.
-
If the global variable is used as a dependencies of the other router. If I want to the reset the global variable in a global_var = {}
@app.post(...)
async func(dependency=Dependencies(global_var))
@app.get("/reload")
# here to change the global var |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
Receive a message (AbstractIncomingMessage) from a RabbitMQ Queue.
Update data1 inside on_message and print it. The output is the expected.
Try to read this data by triggering the endpoint "/{abc}/example", the output is the empty dict.
I want it to output the msg received from the RabbitMQ Queue.
Operating System
Linux
Operating System Details
No response
FastAPI Version
0.1.0
Python Version
3.9
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions