Python 如何在Flask micro framework中创建单例对象
我正在为Python 如何在Flask micro framework中创建单例对象,python,flask,rabbitmq,Python,Flask,Rabbitmq,我正在为Producer创建一个类,它将消息推送到RabbitMQ。它使用了pika模块。 我想创建一个处理程序,以便控制与Rabbit MQ交互的连接数 是否有一种方法可以将此添加到app\u上下文中,然后再参考该上下文,或者是否有一种方法可以使用init\u app来定义此处理程序 任何代码片段都会有很大帮助。在Python中,在大多数情况下不需要使用单例模式,因为Python模块本质上是单例的。但你还是可以用的 class Singleton(object): _instance
Producer
创建一个类,它将消息推送到RabbitMQ
。它使用了pika
模块
。
我想创建一个处理程序,以便控制与Rabbit MQ交互的连接数
是否有一种方法可以将此添加到app\u上下文中,然后再参考该上下文,或者是否有一种方法可以使用init\u app
来定义此处理程序
任何代码片段都会有很大帮助。在Python中,在大多数情况下不需要使用单例模式,因为Python模块本质上是单例的。但你还是可以用的
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
要将Flask(或任何其他web框架)应用程序用作singleton,只需像这样尝试
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
或者继承Flask
类并使其自身成为一个单例。在Python中,在大多数情况下不需要使用单例模式,因为Python模块本质上是单例的。但你还是可以用的
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
要将Flask(或任何其他web框架)应用程序用作singleton,只需像这样尝试
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
或者继承Flask
类并使其自身成为单例