Global variable is not updated inside @get decorator
See original GitHub issueFirst Check
- I added a very descriptive title to this issue.
- I used the GitHub search to find a similar issue and didn’t find it.
- I searched the FastAPI documentation, with the integrated search.
- I already searched in Google “How to X in FastAPI” and didn’t find any information.
- I already read and followed all the tutorial in the docs and didn’t find an answer.
- I already checked if it is not related to FastAPI but to Pydantic.
- I already checked if it is not related to FastAPI but to Swagger UI.
- I already checked if it is not related to FastAPI but to ReDoc.
Commit to Help
- I commit to help with one of those options 👆
Example Code
import pika
import json
from fastapi import FastAPI
from aio_pika import connect
from aio_pika.abc import AbstractIncomingMessage
import asyncio
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost'))
channel = connection.channel()
app = FastAPI()
data1 = {}
async def on_message(message: AbstractIncomingMessage) -> None:
msg = json.loads(message.body)
global data1
data1 = {
'destination' : msg['destination'],
'origin' : msg['origin'],
'method' : msg['method'],
'type' : msg['type'],
'content' : msg['content']
}
print(data1)
@app.get("/{abc}/example")
async def example(abc: int):
global data1
return data1
async def main():
connection_consumer = await connect("amqp://guest:guest@localhost/")
async with connection_consumer:
# Creating a channel
channel = await connection_consumer.channel()
# Declaring queue
queue_4 = await channel.declare_queue("QUEUE4")
# Start listening the queue
await queue_4.consume(on_message, no_ack=True)
print(" [*] Waiting for messages. To exit press CTRL+C")
await asyncio.Future()
if __name__ == '__main__':
asyncio.run(main())
Another script to send messages to QUEUE4
import pika
import json
connection = pika.BlockingConnection(
pika.ConnectionParameters('localhost'))
channel = connection.channel()
channel.queue_declare(queue='QUEUE4')
def main():
msg = {
'destination' : 'string',
'origin' : 'string',
'method' : 'string',
'type' : 'string',
'content' : 'string'
}
channel.basic_publish(exchange='', routing_key='QUEUE4', body=json.dumps(msg))
if __name__ == "__main__":
main()
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
Issue Analytics
- State:
- Created a year ago
- Comments:7 (4 by maintainers)
Top Results From Across the Web
Python decorator does not recognize global variable
The main issue is the decorator is created when the class is made. So the outside decorator is called before you set the...
Read more >Global keyword in Python - GeeksforGeeks
A global keyword is a keyword that allows a user to modify a variable outside the current scope. It is used to create...
Read more >How to make a global variable update across different ... - Quora
However, first make sure you really need a global variable. A global constant is pretty common, but a global variable tends to often...
Read more >Programming FAQ — Python 3.11.1 documentation
What are the rules for local and global variables in Python? Why do lambdas defined in a loop with different ... How do...
Read more >Can you change a global variable's value from within a function?
This is a conceptual question rather than one specifically about the lesson. I understand the idea that a local variable is independent of...
Read more >Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start FreeTop Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
Top GitHub Comments
Thanks for the hint. I solved my problem following the issue on this link https://github.com/tiangolo/fastapi/issues/543
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.