pythonpika

Python 3: TypeError: Can't instantiate abstract class BaseConnection with abstract method create_connection


I am upgrading some very old Python code from Python 2 to Python 3. There is a simple method to check rabbitmq connection using Pika.

    from contextlib import closing
    from pika import URLParameters, BaseConnection

    def check_rabbitmq(self):
        conn_params = URLParameters(self.config.rabbitmq_params['amqp.url'])
        with closing(BaseConnection(conn_params)):
            return True

However, in Python 3 it returns

TypeError: Can't instantiate abstract class BaseConnection with abstract method create_connection I feel like I'm missing something obvious.


Solution

  • As per the error, Can't instantiate abstract class BaseConnection with abstract method create_connection. For that what we can do is to use one of its concrete subclasses for establishing a connection, such as BlockingConnection. using that below is the modified chunk of code:

    def check_rabbitmq(self):
        conn_params = pika.URLParameters(self.config.rabbitmq_params['amqp.url'])
        with pika.BlockingConnection(conn_params) as connection:
            return True
    

    Make sure you also import pika at the top.