celery 4.3.0:从当前任务中获取变量
celery 4.3.0 : get variable from inside current task
我的任务是在数据库中批量插入或删除对象:
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 即使对象插入运行顺利。谁能给我解释一下为什么?
谢谢
在这里找到答案:
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'
我的任务是在数据库中批量插入或删除对象:
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 即使对象插入运行顺利。谁能给我解释一下为什么?
谢谢
在这里找到答案:
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'