【问题标题】:celery 4.3.0 : get variable from inside current taskcelery 4.3.0:从当前任务中获取变量
【发布时间】:2019-12-29 13:29:54
【问题描述】:

我有这个任务,旨在批量插入或删除数据库中的对象:

views.py

from .tasks import run_task_with
def index():
    # some code to retrieve obj_list
    run_task_with(insert_obj, obj_list).delay()
    return HttpResponseRedirect('/app_root/')

tasks.py

@shared_task
def run_task_with(func, queryset):
    cache.add('current_task_id', run_task_with.request.id)
    obj_numb = len(queryset)
    r = map(func, queryset)
    for i, obj in enumerate(r):
        sleep(0.1)
        progress_percent = int(round(float(i) / float(obj_numb) * 100))
        current_task.update_state(
            state='PROGRESS',
            meta={'progress_percent': progress_percent}
        )

但是 run_task_with.request.id 即使在对象插入运行顺利时也会继续返回 None。谁能给我解释一下为什么?

谢谢

【问题讨论】:

    标签: django python-3.x celery


    【解决方案1】:

    在这里找到答案:Celery does not registering tasks

    from django.apps import apps 
    app.autodiscover_tasks(lambda: [n.name for n in apps.get_app_configs()])
    

    对于附属问题(能够将函数 func 传递给任务):

    CELERY_ACCEPT_CONTENT = ['json', 'pickle']
    CELERY_TASK_SERIALIZER = 'pickle'
    

    【讨论】:

      猜你喜欢
      • 2011-03-19
      • 2013-12-09
      • 1970-01-01
      • 2018-11-27
      • 1970-01-01
      • 1970-01-01
      • 2015-11-19
      • 2015-05-06
      • 2013-09-09
      相关资源
      最近更新 更多