用于存储不可变对象的 Django 全局变量
Django global variable to store immutable object
我正在尝试使用 Django 在 Webhook 模式下设置 python-telegram-bot
库。这应该按如下方式工作:在 Django 启动时,我对 python-telegram-bot
进行了一些初始设置,结果得到一个 dispatcher
对象。 Django 监听 /telegram_hook
url 并从 Telegram 服务器接收更新。接下来我要做的是将更新传递给启动时创建的 dispatcher
的 process_update
方法。它包含所有解析逻辑并调用设置期间指定的回调。
问题是dispatcher
对象需要全局保存。我知道全局状态是 evil 但这并不是真正的全局状态,因为 dispatcher
是不可变的。但是,我仍然不知道把它放在哪里以及如何确保它在设置阶段完成后对所有线程可见。所以问题是如何在设置后正确保存 dispatcher
以从 Django 的 viewset
?
调用它
P.S。我知道我可以使用内置网络服务器或使用轮询或其他方式。但是,我有理由使用 Django,无论如何我想知道如何处理这样的情况,因为当我需要在全局范围内存储在启动时创建的不可变对象时,这不是我能想象的唯一情况。
看来你需要像这样的线程安全单例https://gist.github.com/werediver/4396488 or http://alacret.blogspot.ru/2015/04/python-thread-safe-singleton-pattern.html
import threading
# Based on tornado.ioloop.IOLoop.instance() approach.
# See https://github.com/facebook/tornado
class SingletonMixin(object):
__singleton_lock = threading.Lock()
__singleton_instance = None
@classmethod
def instance(cls):
if not cls.__singleton_instance:
with cls.__singleton_lock:
if not cls.__singleton_instance:
cls.__singleton_instance = super(SingletonMixin, cls).__new__(cls)
return cls.__singleton_instance
我正在尝试使用 Django 在 Webhook 模式下设置 python-telegram-bot
库。这应该按如下方式工作:在 Django 启动时,我对 python-telegram-bot
进行了一些初始设置,结果得到一个 dispatcher
对象。 Django 监听 /telegram_hook
url 并从 Telegram 服务器接收更新。接下来我要做的是将更新传递给启动时创建的 dispatcher
的 process_update
方法。它包含所有解析逻辑并调用设置期间指定的回调。
问题是dispatcher
对象需要全局保存。我知道全局状态是 evil 但这并不是真正的全局状态,因为 dispatcher
是不可变的。但是,我仍然不知道把它放在哪里以及如何确保它在设置阶段完成后对所有线程可见。所以问题是如何在设置后正确保存 dispatcher
以从 Django 的 viewset
?
P.S。我知道我可以使用内置网络服务器或使用轮询或其他方式。但是,我有理由使用 Django,无论如何我想知道如何处理这样的情况,因为当我需要在全局范围内存储在启动时创建的不可变对象时,这不是我能想象的唯一情况。
看来你需要像这样的线程安全单例https://gist.github.com/werediver/4396488 or http://alacret.blogspot.ru/2015/04/python-thread-safe-singleton-pattern.html
import threading
# Based on tornado.ioloop.IOLoop.instance() approach.
# See https://github.com/facebook/tornado
class SingletonMixin(object):
__singleton_lock = threading.Lock()
__singleton_instance = None
@classmethod
def instance(cls):
if not cls.__singleton_instance:
with cls.__singleton_lock:
if not cls.__singleton_instance:
cls.__singleton_instance = super(SingletonMixin, cls).__new__(cls)
return cls.__singleton_instance