Python get variable value outside the function in RabbitMQ

1.3k views Asked by At

Below is the function am using to get messages from producer.py

def callback(ch, method, properties, body):
result = body.decode()
resp = JSONEncoder().encode(result)
json_resp = json.loads(resp)
print(json_resp)
ch.basic_ack(delivery_tag = method.delivery_tag)
channel.stop_consuming()

This prints out the expected the result, but what am looking for is to get variable json_resp outside of callback function for further processing

2

There are 2 answers

0
shashank On BEST ANSWER

make that variable global or you can store it in any Database or file, you can also use Python Data Structures like Dictionary, Lists initialise this outer side of function and append the value accordingly.

2
Kostas Christopoulos On

You can the json_resp value at the end of you method. Otherwise, you could call a function with json_resp as parameter to execute your further processing

1)

def callback(ch, method, properties, body):
    result = body.decode()
    resp = JSONEncoder().encode(result)
    json_resp = json.loads(resp)    
    print(json_resp)
    ch.basic_ack(delivery_tag = method.delivery_tag)
    channel.stop_consuming()
    return json_resp


responce = callback(ch, method, properties, body)
print responce

2)

def callback(ch, method, properties, body):
    result = body.decode()
    resp = JSONEncoder().encode(result)
    json_resp = json.loads(resp)    
    print(json_resp)
    ch.basic_ack(delivery_tag = method.delivery_tag)
    channel.stop_consuming()
    my_process_func(json_resp)

you can also treat the var as a global variable as shown in here, something i personally don't really like