1

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

deepak murthy
  • 411
  • 3
  • 6
  • 21

2 Answers2

4

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.

shashank
  • 1,133
  • 2
  • 10
  • 24
0

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

  • in the first point after return json_resp. i tried to access outside the function like print(json_resp) throwed and error - NameError: name 'json_resp' is not defined. – deepak murthy Sep 13 '17 at 10:57
  • if you call the method as in the editted answer it will be ok. In case you don't call directly the method just use the second way. – Kostas Christopoulos Sep 13 '17 at 18:02