Search code examples
pythonrabbitmqpikapython-pika

SelectConnection does not connect to rabbitmq


I am new in Python programming, so I am trying to consume two rabbitmq queues using pika, but using SelectConnection raises an exception IndexError: tuple index out of range An invalid channel number has been specified, but if I use BlockingConnection I am able to successfully consume the queue. Some information: 1 - I am using the pika website async example 2 - My RabbitMQ is running with docker from docker hub oficial image

Here my code:

import pika

if __name__ == '__main__':
    def callback(channel, method, properties, body):
        print(body)
        channel.basic_ack(delivery_tag=method.delivery_tag)

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


    def on_channel_open(channel):
        print("on channel open")
        channel.basic_consume(callback, queue='hello')
        channel.basic_consume(callback, queue='poc')


    parameters = pika.URLParameters('amqp://guest:guest@localhost:5672/%2F')
    connection = pika.SelectConnection(parameters=parameters,on_open_callback=on_open)

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

What am I doing wrong?


Solution

  • You're using an old version of the document, please refer to the latest site:

    https://pika.readthedocs.io/en/latest/examples.html

    You need to add on_open_callback:

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

    Otherwise the first parameter is a channel number.

    You can also find the correct usage by looking at Pika's source code:

    https://github.com/pika/pika

    This will be resolved in the next version of Pika, 1.1.0