1

I am creating a class for Producer which pushes messages to RabbitMQ. It makes use of pika module. I would like to create a handler so that I have control over the number of connections that interact with Rabbit MQ.

Is there a way we can add this to app_context and later refer to that or is there way that we use init_app to define this handler.

Any code snippet would be of really good help.

Vasucd
  • 357
  • 2
  • 10
Varad
  • 920
  • 10
  • 25

1 Answers1

5

In Python, using singleton pattern is not needed in most cases, because Python module is essentially singleton. But you can use it anyway.

class Singleton(object):
    _instance = None

    def __init__(self):
        raise Error('call instance()')

    @classmethod
    def instance(cls):
        if cls._instance is None:
            cls._instance = cls.__new__(cls)
            # more init operation here
        return cls._instance

To use Flask (or any other web framework) app as singleton, simply try like this.

class AppContext(object):
    _app = None

    def __init__(self):
        raise Error('call instance()')

    @classmethod
    def app(cls):
        if cls._app is None:
            cls._app = Flask(__name__)
            # more init opration here
        return cls._app

app = AppContext.app() # can be called as many times as you want

Or inherite Flask class and make itself as a singleton.

DumTux
  • 668
  • 1
  • 9
  • 24