Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass arbitrary args to a callback function in RabbitMQ?

I am trying to pass a callback function in the RabbitMQ basic_consume method that requires extra arguments.

For example, the callback function signature in RabbitMQ is:

def callback(ch, method, properties, body):
    pass

I want something like:

def callback(ch, method, properties, body, x, y):
    # do something with x and y

Then pass it down as a callback in basic_consume

channel.queue_declare(queue=queue_name, durable=True)
channel.basic_qos(prefetch_count=1)
channel.basic_consume(queue=queue_name, on_message_callback=callback)
channel.start_consuming()

How can I achieve something like that?

like image 344
Dimitris Poulopoulos Avatar asked Dec 14 '25 05:12

Dimitris Poulopoulos


1 Answers

You can use currying to generate a callback:

def generateCallback(x, y):
    def callback(ch, method, properties, body):
        print(
            "callback for ch={}, method={}, properties={}, body={}, x={}, y={} called".format(
                ch, method, properties, body, x, y
            )
        )

    return callback


if __name__ == "__main__":
    callback = generateCallback(1, 2)

    callback("ch", "method", "properties", "body")

Output:

callback for ch=ch, method=method, properties=properties, body=body, x=1, y=2 called

Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!