Django celery beat не смог найти приложение для планирования задач

#python #django #rabbitmq #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}amp;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-сервер для запросов задач.

  • Мой rabbitmq-сервер активен все время.
  • Другие задачи с сельдереем работают абсолютно нормально.(Я попытался реализовать функцию электронной почты, которая хорошо работает с сельдереем).

Я начинаю работать с сельдереем и бью с помощью

 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.

Комментарии:

1. Вы используете Windows? На самом деле у сельдерея есть некоторые проблемы с работой в Windows, поэтому я использую эту команду в качестве обходного пути — celery -A project worker -l INFO -P solo . Смотрите, что я добавляю -P solo в команду. Не используйте это в производстве. На вашем сервере Linux обычная команда будет работать нормально.

2. Я уже на linux

Ответ №1:

Вы явно назвали задачу "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. Не задавайте имя задачи явно. Сельдерей установит для него имя по умолчанию на основе имен модулей и имени функции, как указано в документации. Расписание биений остается прежним (при 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'),
        },
    }
     

Чтобы подчеркнуть, выберите только одно из этих 2 решений, потому что выполнение обоих, очевидно, все равно не удастся по одной и той же причине.

Кроме того, обратите внимание, что при использовании Django рекомендуется использовать декоратор @shared_task, поэтому вы можете изменить свои задачи на:

 from celery import shared_task


@shared_task
def add_trades_to_database():
   ...
 

Комментарии:

1. Работает отлично. Хорошее объяснение.