如何 运行 与 Celery 并行的 Django 方法?

How to run a Django method in parallel with Celery?

我的模型上有一个方法 update_prices() 我想 运行 与 Celery 并行,但我不知道如何让它工作。如您所见,.s() 存在问题,因为它抱怨 'function' object has no attribute 's'。我该怎么做?

这是我的代码:

@celery.app.task(name='Update')
def update():

    # list of arguments
    exchanges_list = Exchange.objects.filter(status='ok').values_list('name', flat=True)

    # the function that execute the method
    def update_prices(name):
        Exchange.objects.get(name=name).update_prices()

    gp = group([update_prices.s(name) for name in exchanges_list])()

稍微不同的方法会产生相同的错误:

gp = group(update_prices.s(name) for ex in exchanges_list)()
gp = group(update_prices.(name).s() for ex in exchanges_list)()
gp = group(Exchange.objects.get(name=name).update_prices().s() for ex in exchanges_list)()

这与 Celery documention 简单小组任务中的示例非常相似:

res = group(add.s(i, i) for i in range(10))()

谢谢

我回答了我的问题,因为我终于找到了导致错误的原因。方法 update_prices(name) 需要一个像这样的专用装饰器,它工作得很好!

@celery.app.task
def update_prices(name):
        Exchange.objects.get(name=name).update_prices()