【问题标题】:Bound task in celery is not able to access instance variable in django projectcelery 中的绑定任务无法访问 django 项目中的实例变量
【发布时间】:2019-05-14 13:45:20
【问题描述】:

我使用官方文档在我的 django 项目中设置了 celery http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html#using-celery-with-django

所以我的MyApp/tasks.py 有内容

from celery import shared_task

class Someclass():
    def __init__(self, x, y):
        self.x = x
        self.y = y

    @shared_task(bind=True) 
    def func1(self):
        '''This does not work'''
        return self.x + self.y


    @shared_task(bind=True)
    def func2(self, a, b):
        '''This works well'''
        return a + b

当我跑步时

In [9]: o = Someclass(3, 4)    
In [10]: o.func1.delay()
Out[10]: <AsyncResult: afc6b151-d71c-4f46-a916-6917f98c681f>

我得到了错误

AttributeError: 'func1' object has no attribute 'x'

当我跑步时

In [11]: o.func2.delay(3, 4)
Out[11]: <AsyncResult: 3b227f00-8d9c-472b-b7d8-8b4b6261f689>

这很好用

我怎样才能使func1 工作,以便它可以使用实例变量,例如xy?

【问题讨论】:

    标签: django task celery background-task


    【解决方案1】:
    from celery import shared_task
    
    @shared_task(bind=True)
    def func(self, a, b):
        return a + b
    
    
    class Someclass():
        def __init__(self, x, y):
            self.x = x
            self.y = y
    
        def func1(self):
            return func.delay(self.x, self.y)
    

    【讨论】:

    • 虽然这段代码可以回答问题,但最好解释一下如何解决问题,并提供代码作为示例或参考。仅代码的答案可能会令人困惑且缺乏上下文。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-09-22
    • 1970-01-01
    • 2012-01-27
    • 2017-03-10
    • 2021-12-21
    • 1970-01-01
    • 2011-09-15
    相关资源
    最近更新 更多