Django celery beat 无法找到应用程序来安排任务

Django celery beat not able to locate app to schedule task

我正在尝试在 celery 中安排任务。

celery.py 在主项目目录中

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from celery.schedules import crontab

os.environ.setdefault('DJANGO_SETTINGS_MODULE','example_api.settings')

app = Celery('example_api')

app.config_from_object('django.conf:settings',namespace="CELERY")

app.conf.beat_schedule = {
    'add_trades_to_database_periodically': {
        'task': 'transactions.tasks.add_trades_to_database',
        'schedule': crontab(minute='*/1'),
        # 'args': (16,16),
    },
}

app.autodiscover_tasks()

该项目有一个名为交易的应用程序。

里面的函数transactions/tasks.py

@task(name="add_trades_to_database")
def add_trades_to_database():
    start_date = '20000101' #YYYYDDMM
    end_date = '20150101'
    url = f'https://api.example.com/trade-retriever-api/v1/fx/trades?fromDate={start_date}&toDate={end_date}'
    content = get_json(url)
    print(content)
    save_data_to_model(content,BulkTrade)

settings.py

"""
Django settings for nordea_api project.

Generated by 'django-admin startproject' using Django 3.2.7.

For more information on this file, see
https://docs.djangoproject.com/en/3.2/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.2/ref/settings/
"""

from pathlib import Path
import os
import environ

env = environ.Env()
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
env.read_env(env.str('BASE_DIR', '.env'))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'example'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',

    'rest_framework',
    'rest_framework.authtoken',
    'rest_auth',
    'rest_auth.registration',

    'allauth',
    'allauth.account',
    'allauth.socialaccount',

    'corsheaders',

    'transactions.apps.TransactionsConfig',

    'django_celery_beat',
]

# REST_FRAMEWORK = {
#     'DEFAULT_PERMISSION_CLASSES':[
#         'rest_framework.permissions.IsAuthenticated',
#     ]
# }

CELERY_TIMEZONE = "UTC"
# CELERY_BEAT_SCHEDULER = 'django_celery_beat.schedulers:DatabaseScheduler'
CELERY_TASK_SERIALIZER = 'json'
CELERY_RESULT_SERIALIZER = 'json'

DEFAULT_AUTHENTICATION_CLASSES = [
    'rest_framework.authentication.SessionAuthentication',
    'rest_framework.authentication.TokenAuthentication',
]

EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = True
EMAIL_PORT = 587
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = os.environ.get('EMAIL')
EMAIL_HOST_PASSWORD = os.environ.get('EMAIL_PASSWORD')
DEFAULT_FROM_EMAIL = os.environ.get('EMAIL')

SITE_ID = 1

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'example_api.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'example_api.wsgi.application'


# Database
# https://docs.djangoproject.com/en/3.2/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.postgresql_psycopg2',
        'NAME': 'example_transaction',
        'USER': 'myUser',
        'PASSWORD': os.environ.get('DATABASE_PASSWORD'),
        'HOST':'localhost',
        'PORT':'',
    }
}


# Password validation
# https://docs.djangoproject.com/en/3.2/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/3.2/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.2/howto/static-files/

STATIC_URL = '/static/'

# Default primary key field type
# https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'


我正在为任务队列使用 rabbitmq-server。

我启动 celery worker 并使用

celery -A project worker -l info
celery -A project beat -l info

工人终端出现如下错误

The full contents of the message body was:
'[[], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (77b)
Traceback (most recent call last):
  File "/home/......./env/lib/python3.8/site-packages/celery/worker/consumer/consumer.py", line 581, in on_task_received
    strategy = strategies[type_]
KeyError: 'transactions.tasks.add_trades_to_database'

我正在使用 ubuntu。

您已明确命名任务 "add_trades_to_database"

@task(name="add_trades_to_database")
def add_trades_to_database():
    ...

然而,您正在使用名称 "transactions.tasks.add_trades_to_database"

安排任务
app.conf.beat_schedule = {
    'add_trades_to_database_periodically': {
        'task': 'transactions.tasks.add_trades_to_database',
        'schedule': crontab(minute='*/1'),
    },
}

您可以选择的解决方案:

  1. 不要明确地为任务设置名称。 Celery 会根据模块名称和函数名称为其设置默认名称 documented。节拍时间表保持不变(假设 add_trades_to_database 位于 my_proj/transactions/tasks.py::add_trades_to_database
    @task
    def add_trades_to_database():
        ...
    
  2. 或者您可以只更改节拍时间表以引用明确设置的名称。
    app.conf.beat_schedule = {
        'add_trades_to_database_periodically': {
            'task': 'add_trades_to_database',
            'schedule': crontab(minute='*/1'),
        },
    }
    

强调一下,只从这两个解决方案中选择一个,因为两者都做显然仍然会因同样的原因而失败。

此外,请注意,使用 Django 时,惯例是使用装饰器 @shared_task,因此您可能希望将任务更改为:

from celery import shared_task


@shared_task
def add_trades_to_database():
   ...