django - 在 Python 中使用 celery 调用类的实例方法
问题描述
在旧版本的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运行preProcess
和process
类。postProcess
Client1Service
如果我得不到任何解决方案,那么我将不得不在一些外部 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
推荐阅读
- angular - angular 8 firefox 50 和 IE 11 不工作
- java - 是否可以通过使用来自 Web 服务器 api 的 MpAndroid 来显示图表?
- pandas - 我想根据相同的 Dateframe 计算值。新值必须附加到 Dateframe 。怎么做?
- java - 如何在java中使用列名读取csv
- ruby-on-rails - 根据 Rails 中的路线更改嵌套表单部分字段
- objective-c - CoreML 和 YOLOv3 性能问题
- sql-server-2008-r2 - 使用数据生成脚本时,索引超出范围必须是非负数且小于集合的大小
- android - getItemViewType 没有按预期工作
- r - 如何使用 pheatmap 修复行顺序?
- reactjs - what does the error mean by TypeError: Cannot read property 'join' of undefined