fastapi icon indicating copy to clipboard operation
fastapi copied to clipboard

Global variable is not updated inside @get decorator

Open CrazyGalEt opened this issue 1 year ago • 7 comments

First Check

  • [X] I added a very descriptive title to this issue.
  • [X] I used the GitHub search to find a similar issue and didn't find it.
  • [X] I searched the FastAPI documentation, with the integrated search.
  • [X] I already searched in Google "How to X in FastAPI" and didn't find any information.
  • [X] I already read and followed all the tutorial in the docs and didn't find an answer.
  • [X] I already checked if it is not related to FastAPI but to Pydantic.
  • [X] I already checked if it is not related to FastAPI but to Swagger UI.
  • [X] I already checked if it is not related to FastAPI but to ReDoc.

Commit to Help

  • [X] 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

CrazyGalEt avatar Jul 29 '22 02:07 CrazyGalEt

Not sure if this is a FastAPI issue.

iudeen avatar Jul 29 '22 07:07 iudeen

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"
}

JarroVGIT avatar Jul 29 '22 08:07 JarroVGIT

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"
}

thanks for the reply, but that is not what im achieving to do.

CrazyGalEt avatar Jul 29 '22 13:07 CrazyGalEt

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.

JarroVGIT avatar Jul 29 '22 13:07 JarroVGIT

I have edited the code. To run the code you need to run a server rabbitmq.

CrazyGalEt avatar Jul 29 '22 13:07 CrazyGalEt

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 uvicorn main:app it would not work the setup you have. You need to run both your consumer and server in same process.

iudeen avatar Jul 29 '22 15:07 iudeen

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 uvicorn main:app it would not work the setup you have. You need to run both your consumer and server in same process.

Thanks for the hint. I solved my problem following the issue on this link https://github.com/tiangolo/fastapi/issues/543

CrazyGalEt avatar Jul 30 '22 14:07 CrazyGalEt