无法配置格式化程序 'json':无法解析 'app_name.utils.logging.JSONFormatter':无法导入名称 'Celery'

Unable to configure formatter 'json': Cannot resolve 'app_name.utils.logging.JSONFormatter': cannot import name 'Celery'

我正在尝试将 celery 包含到我们的 Django 应用程序中,但正在为设置而苦苦挣扎。 到目前为止,我对 Whosebug/google 的所有搜索都告诉我我有循环依赖,但我看不到它。文档 https://docs.celeryproject.org/en/stable/getting-started/first-steps-with-celery.html 清楚地使用 from celery import Celery

我定义了: app_name/app_name_celery.py

from celery import signals, Celery
import os
from django.conf import settings
# disable celery logging so that it inherits from the configured root logger
@signals.setup_logging.connect
def setup_celery_logging(**kwargs):
    pass

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings.local")

# Create default Celery app
app = Celery('app_name')

# namespace='CELERY' means all celery-related configuration keys
# should be uppercased and have a `CELERY_` prefix in Django settings.
# https://docs.celeryproject.org/en/stable/userguide/configuration.html
app.config_from_object("django.conf:settings", namespace="CELERY")

# When we use the following in Django, it loads all the <appname>.tasks
# files and registers any tasks it finds in them. We can import the
# tasks files some other way if we prefer.
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS)

另外,我用

定义了app_name/my_app_config.py
from django.apps import AppConfig


class MyAppConfig(AppConfig):
    # ...

    def ready(self):
        # Import celery app now that Django is mostly ready.
        # This initializes Celery and autodiscovers tasks
        import app_name.app_name_celery

最后,我已经添加到我的 __init__.py:

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .app_name import app as celery_app

__all__ = ('celery_app',)

此外,此 pr 的日志记录设置未更改,但此处为:

LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
    'formatters': {
        'json': {
            '()': 'app_name.utils.logging.JSONFormatter'
        }
    },
    'handlers': {
        'console': {
            'level': 'DEBUG',
            'class': 'logging.StreamHandler',
            'formatter': 'json'
        }
    },
    'loggers': {
        'ddtrace': {
            'level': 'WARNING'
        }
    },
    'root': {
        'level': 'DEBUG',
        'handlers': ['console']
    }
}

任何人都可以看到循环依赖或我可能还遗漏了什么吗?

您正在尝试导入 django 设置

app_name/app_name_celery.py

from celery import signals, Celery
import os
from django.conf import settings # This line here

此外,您不需要将 celery 导入到您的应用程序配置中。

自动发现在 app/tasks.py、app_2/tasks.py 等中查找任务