我正在尝试使用芹菜创建定期任务,每天从网上下载一些文件。但是当我尝试在创建任务的文件中导入库时,我遇到了问题。我收到一个错误Received unregistered task of type 'download_data_nist.tasks.download_data'
.如果我删除导入, 任务执行时没有错误。
我已经在 settings.py 配置了芹菜:
from celery.schedules import crontab
CELERY_BROKER_URL = 'amqp://localhost'
CELERY_TIMEZONE = 'CET'
CELERY_BEAT_SCHEDULE = {
'task-number-one': {
'task': 'download_data_nist.tasks.download_data',
'schedule': crontab(minute='*/1'),
},
}
我在应用程序的根文件夹中创建了 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', 'AplikacijaZaPregledRanljivosti.settings')
app = Celery('AplikacijaZaPregledRanljivosti')
# Using a string here means the worker don't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
# should have a `CELERY_` prefix.
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))
我将这段代码添加到根文件夹中的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']
当我收到错误时,我的 tasks.py 如下所示:
from __future__ import absolute_import, unicode_literals
from celery import task
import json
import re
import requests
import zipfile
from django.conf import settings
@task()
def download_data():
return "Data downloaded"
执行任务时 tasks.py 如下所示:
from __future__ import absolute_import, unicode_literals
from celery import task
@task()
def download_data():
return "Data downloaded"
如何导入库而不会出错?
当你从芹菜工人那里得到错误时unregistered task
你需要确保两件事:
- 在
settings.py
中通知芹菜您的应用模块。这也将帮助您了解可能遇到的依赖项错误:
# settings.py
CELERY_IMPORTS = (
'your_app_name.tasks'
)
- 确保已满足虚拟环境中的所有依赖项库等。在这种情况下,您需要确保已安装
requests
等。