如何解决在Django中调用.delay后,芹菜任务挂起
从Django应用程序调用导入任务的.delay()
方法时,进程陷入困境,请求从未完成。
我们在控制台上也没有收到任何错误。
用pdb设置set_trace()
会产生相同的结果。
对以下问题进行了审查,这些问题无助于解决问题:
Calling celery task hangs for delay and apply_async
celery .delay hangs (recent,not an auth problem)
例如:
backend / settings.py
CELERY_BROKER_URL = os.environ.get("CELERY_BROKER",RABBIT_URL)
CELERY_RESULT_BACKEND = os.environ.get("CELERY_BROKER",RABBIT_URL)
backend / celery.py
from __future__ import absolute_import,unicode_literals
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE','backend.settings')
app = Celery('backend')
app.config_from_object('django.conf:settings',namespace='CELERY')
# Load task modules from all registered Django app configs.
app.autodiscover_tasks()
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
app / tasks.py
import time
from celery import shared_task
@shared_task
def upload_file(request_id):
time.sleep(request_id)
return True
app / views.py
from rest_framework.views import APIView
from .tasks import upload_file
class UploadCreateAPIView(APIView):
# other methods...
def post(self,request,*args,**kwargs):
id = request.data.get("id",None)
# business logic ...
print("Going to submit task.")
import pdb; pdb.set_trace()
upload_file.delay(id) # <- this hangs the runserver as well as the set_trace()
print("Submitted task.")
解决方法
问题在于使用Django安装celery应用程序。我们需要确保在以下文件中导入了celery应用并对其进行了初始化:
backend\__init__.py
from __future__ import absolute_import,unicode_literals
# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app
__all__ = ('celery_app',)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。