连锁和小组任务方法用芹菜

时间:2013-12-02 20:05:06

标签: python django celery django-celery

(是吗?xD)

嗯,我在Celery项目中遇到以下情况。让我把你们全部放在一边。

我有很多任务使用API​​在我们通过Web服务使用的服务中进行一些配置(SOAP,我正在使用suds,但这是另一个故事)。

所以,我意识到所有的任务几乎都是一样的,直到配置的某些方面都是同样的流程:

configure_this - > configure_some_special_case_things - > configure_other_things - > configure_another_set_of_things

由于顺序并不重要,我可以在流程结束时配置特殊情况而没有任何问题,除了“special_case_configurations”之外的所有步骤在所有情况下都是相同的,所以我将这个逻辑抽象为某种东西像这样:

class BaseConfigurator(object):
    def __init__(self, some_args, *args, **kwargs):
        self.shared_state = some_args

    def _configure_this(self):
        #some steps that modifies the shared state

    def _configure_other_things(self):
        #some other steps that modifies the shared state

    def _configure_another_set_of_things(self):
        # another set of steps that modifies the shared state

    def _special_case_steps(self):
        # to be implemented by subclasses
        pass

    def configure(self):
        self._configure_this()
        self._configure_ahother_things()
        self._configure_another_set_of_things()
        self._special_case_steps()

然后......我将这个子类化并实现_special_case_steps

class ParticularConfigurator(BaseConfigurator):
    def __init__(self, some_args, *args, **kwargs):
        super(ParticularConfigurator, self).__init__(self, some_args, *args, **kwargs)

    def _special_case_steps(self):
        # actual implementation, this overwrites the parent's "pass"

所以,它以前的工作方式是几个“配置器”任务,称为“一般配置器”任务和“特殊情况配置器”任务,以便顺序进入celery.chain,所以,我有很多重复代码,我认为这种方式更优雅,这样我可以正确地重用我的“配置”方法。

我知道这一点 using class methods as celery tasks

所有命名警告,但出于任何原因,我试图对一些task_methods进行分组和链接,并且我在我的任务代码中没有直接使用的对象得到了几个酸洗错误,我在被调用的函数中使用它们我的task_method。

我通过在一个单独的任务中实例化我的配置器类来实现它,该任务区分我们配置的情况并决定调用哪个配置器。

@celery.task(queue='user_tasks', max_retries=3, default_retry_delay=120, on_success=handlers.configuration_success)
def run_configuration(case, data):
    switch = {
        'default': DefaultConfigurator # I know, this is not declared but it's just for the example, let's pretend it is a subclass of BaseConfigurator :-)
        'custom': ParticularConfigurator
    }
    switch[case](data).configure()

现在,我很担心这一点,因为我没有利用celery.chain和celery.group的芹菜功能,我想这样我的代码运行速度比我能够链接和分组task_methods慢我是对的吗?

我应该继承Task而不是用实例方法创建任务吗?

感谢您抽出宝贵时间阅读。

0 个答案:

没有答案
相关问题