gpt4 book ai didi

django - 在 Python 中使用 celery 调用类的实例方法

转载 作者:行者123 更新时间:2023-12-05 08:08:10 32 4
gpt4 key购买 nike

旧版本Celery根据 http://docs.celeryproject.org/en/3.1/reference/celery.contrib.methods.html,可以将实例方法转换为 celery 任务,如下例所示

from celery.contrib.methods import task
class X(object):
@task()
def add(self, x, y):
return x + y

我使用的是 Celery 4.1,它默认没有这样的功能。我怎样才能以一些简单的方式自己实现这个功能?

让我举例说明我的要求。

from abc import ABC, abstractmethod

AbstractService(ABC):

def __init__(self, client_id, x, y):
self.client_id = client_id
self.x = x
self.y = y

@abstractmethod
def preProcess(self):
'''Some common pre processing will execute here'''

@abstractmethod
def process(self):
'''Some common processing will execute here'''

@abstractmethod
def postProcess(self):
'''Some common post processing will execute here'''

Client1Service(AbstractService):

def __init__(self, x, y):
super(__class__, self).__init__('client1_id', x, y)

# I want to run this using celery
def preProcess(self):
super().preProcess()

# I want to run this using celery
def process(self):
data = super().process()
# apply client1 rules to data
self.apply_rules(data)
print('task done')

# I want to run this using celery
def postProcess(self):
super().postProcess()

def appy_rules(self, data):
'''Client 1 rules to apply'''
# some logic

我想在 django 中使用 celery 运行 Client1Service 类的 preProcessprocesspostProcess项目。

如果我得不到任何解决方案,那么我将不得不在一些有点困惑的外部 celery 任务中运行 preProcess、process 和 postProcess 的逻辑。
为这个要求建议我一些设计。

最佳答案

尝试使用:

from celery import shared_task
@shared_task(bind=True)
def yourfunction():
dosth()

这里有一个很好的教程:http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html

关于django - 在 Python 中使用 celery 调用类的实例方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51781563/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com