【问题标题】:Django & Celery use a singleton class instance attribute as a globalDjango & Celery 使用单例类实例属性作为全局
【发布时间】:2015-07-03 13:10:50
【问题描述】:

我希望这样做:

我在同一个模块中有两个函数(甚至同一个文件):

def a():
    while(True):
         //do something
         if global_var:
              //do something else!

def b():
    global_var = some_function_result

我得到了使用单例类作为全局存储的想法。

(我确实尝试过使用模块级全局,结果相同)

class Singleton(type):
    _instances = {}

    def __call__(cls, *args, **kwargs):
        if cls not in cls._instances:
            cls._instances[cls] = super(Singleton, cls).__call__(*args, **kwargs)
        return cls._instances[cls]

class MyClass(object):
    __metaclass__ = Singleton

    def __init__(self):
        self.flag = 1

@shared_task
def add_var():
    myclass = MyClass()
    while(1):
        myclass.flag += 1
        print myclass.flag

@shared_task
def print_var():
    myclass = MyClass()
    while(1):
        print myclass.flag

结果:

print_var 一直打印 1,add_var 一直加 1,但它没有反映在 print_var 中

编辑:

未及时提及重要信息: 我在 celery 上运行这些进程——现在我开始明白 celery 和 django 在不同的线程上运行。 但是当我在芹菜中运行两者时,我仍然看不到效果。

【问题讨论】:

    标签: python scope global-variables


    【解决方案1】:

    如果这就是你想要实现的全部,你不需要单例; (静态)类属性将完成这项工作:

    class MyClass(object):
    
        FLAG = 1
    
    @shared_task
    def add_var():
        myclass = MyClass()
        while(1):
            myclass.FLAG += 1
            print( myclass.FLAG )
    
    @shared_task
    def print_var():
        myclass = MyClass()
        while(1):
            print( myclass.FLAG )
    

    【讨论】:

    • 同样的结果。价值似乎没有改变。所以我尝试在 shell 中运行它 - 称为 add_var(),然后在几秒钟后退出 - 标志值是数千 - 现在当我执行 MyClass.FLAG 时,它仍然是 1
    • 那么你的其余代码是做什么的? @shared_task 是什么?
    • Celery - 它使用 .delay() 异步运行
    猜你喜欢
    • 2021-11-22
    • 2011-10-24
    • 2016-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-18
    • 1970-01-01
    相关资源
    最近更新 更多