Django和Celery,AppRegisteredNotReady异常 [英] Django and Celery, AppRegisteredNotReady exception
问题描述
我正在尝试将Celery集成到我的Django项目中.我已经关注了Celery文档,并且可以执行一个简单的Hello World任务.但是,当我尝试将模型导入到任务定义中时,出现了AppRegisteredNotReady异常.我正在寻找有关此异常的一些较早的讨论,但没有最新的讨论.我可能缺少了一些非常简单的内容.
I'm trying to integrate Celery into my Django project. I've followed the Celery docs, and I can execute a simple Hello World task. But when I try to import my models into my task definitions, I am getting the AppRegisteredNotReady exception. I'm finding some older discussions around this exception, but nothing current. I'm probably missing something quite simple.
Python 3.5,Django 1.9,Celery 3.1.23
Python 3.5, Django 1.9, Celery 3.1.23
Celery.py:
Celery.py:
from __future__ import absolute_import
import os
from celery import Celery
from django.conf import settings
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings.local') # pragma: no cover
app = Celery('autopool')
app.config_from_object('django.conf:settings')
app.autodiscover_tasks(lambda: settings.INSTALLED_APPS, force=True)
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request)) # pragma: no cover
自动合并/初始化 .py:
from __future__ import absolute_import
from autopool.celery import app as celery_app # noqa
apps/pools/tasks.py:
apps/pools/tasks.py:
from __future__ import absolute_import
from celery import shared_task
@shared_task
def send_period_mail(period_id):
print("Mail sent for period " + period_id)
我用以下命令启动Celery:
I start Celery with the command:
celery -A autopool worker -l info
从我的角度来看,我执行:
From my view, I execute:
import .tasks send_period_mail
send_period_mail(period_id=period.id)
这一切正常.
但是,当我尝试将模型添加到任务中时:
However when I try to add a model to the task:
from __future__ import absolute_import
from celery import shared_task
from .models import Period
@shared_task
def send_period_mail(period_id):
print("Mail sent for period " + period_id)
现在,当我尝试启动celery时,会收到AppRegisteryNotReady:应用程序尚未加载异常.
Now when I try to start celery, I receive the AppRegisteryNotReady: Apps aren't loaded yet exception.
完整堆栈跟踪: http://pastebin.com/kmJZLHpT
有人知道吗?
推荐答案
由于导入 celery.py
文件时,Django尚未加载应用程序/模型(因此无法导入型号 from .models import Period
)将导入移动到函数内部
Because when the celery.py
file is imported Django haven't loaded the apps/models yet (so it fails to import the model from .models import Period
) move the import inside the function
@shared_task
def send_period_mail(period_id):
from .models import Period
print("Mail sent for period " + period_id)
因此只有在调用函数(并且Django准备就绪)时才会加载
so it will only be loaded when the function is called (and Django is ready)
这篇关于Django和Celery,AppRegisteredNotReady异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!