【问题标题】:Celery can not find periodic tasks after importing librariesCelery 导入库后找不到周期性任务
【发布时间】:2019-12-20 19:07:19
【问题描述】:

我正在尝试使用 celery 创建定期任务,它每天都会从网上下载一些文件。但是当我尝试在创建任务的文件中导入库时遇到问题。我收到一个错误Received unregistered task of type 'download_data_nist.tasks.download_data'。如果我删除导入, 任务执行没有错误。

我已经在settings.py中配置了Celery:

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"

如何导入库而不出错?

【问题讨论】:

  • 您真的需要from __future__ import absolute_import, unicode_literals 行吗?
  • 我从文档中复制了这一行。

标签: python django celery


【解决方案1】:

当您收到来自 celery worker 的 unregistered task 错误时,您需要确保两件事:

  1. settings.py 中通知 celery 您的应用模块。这也将帮助您了解您可能遇到的依赖错误:
# settings.py
CELERY_IMPORTS = (
    'your_app_name.tasks'
)
  1. 确保您已满足虚拟环境等中的所有依赖库。在这种情况下,您需要确保已安装requests 等。

【讨论】:

  • 我忘记安装请求。感谢您的帮助。
猜你喜欢
  • 2018-11-28
  • 1970-01-01
  • 2015-07-14
  • 1970-01-01
  • 2020-09-30
  • 2018-08-03
  • 1970-01-01
  • 2017-06-15
  • 2017-05-11
相关资源
最近更新 更多