Search code examples
pythonrabbitmqpika

How to access information from callback


I just want to know how to get data from within the callback.

import pika


def callback(channel, method, properties, body):
    print(method.get_body())
    print(method.get_properties())
    channel.basic_ack(delivery_tag=method.delivery_tag)

def on_open(connection):
    connection.channel(on_open_callback=on_channel_open)


def on_channel_open(channel):
    channel.basic_consume(on_message_callback = callback, queue='q1')
    channel.basic_consume(on_message_callback = callback, queue='q2')


credentials = pika.PlainCredentials('user', 'password', erase_on_connect=False)
params = pika.ConnectionParameters("localhost", 5672, '/', credentials)

connection = pika.SelectConnection(parameters=params,
                                   on_open_callback=on_open)

try:
    connection.ioloop.start()
except KeyboardInterrupt:
    connection.close()

    connection.ioloop.start()

The output to the two print lines in callback are:

<class 'pika.spec.Basic.Deliver'>
<Basic.Deliver(['consumer_tag=ctag1.2607da3f5f9f4e5592991a16cc0aca6e', 'delivery_tag=1', 'exchange=gatekeeper', 'redelivered=True', 'routing_key=laa'])>

How can I extract the 'routing_key'? Having a look at the source code it led me to believe method.get_properties() would work, but it did not.


Solution

  • Although poorly documented, the callback function will be called with 4 arguments:

    • The channel you consumed with
    • A Method instance (in this case a Deliver instance)
    • A BasicProperties instance
    • A body (bytes)

    The Deliver instance will have an attribute called routing_key. So your function could look like this:

    def callback(channel, method, properties, body):
        print(method.get_body())
        print(method.get_properties())
        print(method.routing_key)
        channel.basic_ack(delivery_tag=method.delivery_tag)
    

    PS. The arguments the callback will be called with are the same as described in here, where they are actually documented.