收到xx类型的未注册任务。该消息已被忽略并被丢弃

时间:2015-03-24 20:07:06

标签: python django celery

我在ubuntu EC2节点上有一个django项目,它执行计算密集型的长时间运行过程,通常需要60秒。我需要缓存结果。我一直在阅读http://www.caktusgroup.com/blog/2014/06/23/scheduling-tasks-celery/http://michal.karzynski.pl/blog/2014/05/18/setting-up-an-asynchronous-task-queue-for-django-using-celery-redis/以及文档。我已经能够在命令行中完成一项基本任务,但现在我正试图将它作为django脚本运行。

现在我的django tp1视图中的代码结构是:

from django.shortcuts import render
from django.http import HttpResponse
from django.views.decorators.csrf import csrf_exempt
from __future__ import absolute_import
from celery import shared_task

@csrf_exempt
def index(request):

    token = str(request.POST.get('token', False))
    calculator(token)
    return HttpResponse(token)

@shared_task
def calculator(token):

    # do calculation
    # store result in cache

    return

在命令行上我跑了:

(env1)ubuntu@ip-172-31-22-65:~/projects/tp$ celery --app=tp.celery:app worker --loglevel=INFO

在收到的消息结尾处:

[2015-03-24 19:49:47,045: ERROR/MainProcess] Received unregistered task of type 'tp1.views.calculator'.
The message has been ignored and discarded.    Did you remember to import the module containing this task? Or maybe you are using relative imports?

我的tasks.py:

from __future__ import absolute_import    

from celery import shared_task    

@shared_task
def test(param):
    return 'The test task executed with argument "%s" ' % param

我怎样才能使这个工作?

1 个答案:

答案 0 :(得分:1)

首先,如果您使用autodiscover,Celery可能无法autodiscover您的tasks.py文件。您是否通过为celery_app任务创建autodiscover文件来配置according to the docs

# project/celery_app.py
from __future__ import absolute_import

import os

from celery import Celery

from django.conf import settings

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings')

app = Celery('project_name')

# Using a string here means the worker will not have to
# pickle the object when using Windows.
app.config_from_object('django.conf:settings')
# YOUR APPLICATION MUST BE LISTED IN settings.INSTALLED_APPS for this to work
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)


@app.task(bind=True)
def debug_task(self):
    print('Request: {0!r}'.format(self.request))

此外,如果您依赖autodiscover,它通常无法找到位于未调用tasks.py的模块中的内容。

因此,除了检查您的配置外,我还会尝试将views.py中的任务移到tasks.py

 # project/app_name/tasks.py
 from celery_app import app
 @app.task()
 def calculator(token):

    # do calculation
    # store result in cache

    return

最后,您可以从tasks.py导入此功能并在您的视图中调用它。

希望有所帮助。