【问题标题】:Apps aren't loaded yet when trying to import model in a celery tasks file尝试在 celery 任务文件中导入模型时尚未加载应用程序
【发布时间】:2018-06-03 21:15:42
【问题描述】:

在任何解释之前,这是我的项目的树

| projectname
|____|__init__.py
|____|celery.py
|____|settings.py
|____|urls.py
|____|wsgi.py
|app1
|app2

这是我的 celery.py

from celery import Celery
from celery import shared_task

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')
app = Celery('projectname')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()

from app1.models import *

@share_task
def tasks():
     ''' '''

每次我尝试使用 from app1.models import * 这一行将 models 导入到 celery.py 文件时,我得到了:

django.core.exceptions.AppRegistryNotReady:应用尚未加载。

本地服务器突然停止工作。 This post 与一个类似的问题有关,但不确定是不是这里的情况。

我想要将一些模型导入文件,以便我可以将它们用于一些查询。

我对可能出了什么问题有了一点线索,但不确定。

viewsmodels.py
views 导入东西 celery.py strong> 喜欢要执行的任务
celery.py 尝试从 models 导入内容。

所以我觉得像蛇一样咬自己尾巴的圆圈很奇怪。

【问题讨论】:

    标签: python django celery


    【解决方案1】:

    问题是当您尝试在 Django 加载配置()之前上传您的任务

    <b>from app1.models import *</b>
    os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectname.settings')
    app = Celery('projectname')
    
    app.config_from_object('django.conf:settings', namespace='CELERY')
    app.autodiscover_tasks()
    

    当然,Celery 会检测 celery.py 文件中的任务,请记住,您已经导入了从 celery.py__init__.py 的所有内容,以便让 Django 在每次项目启动时加载它们(Celery 的东西,...)。

    __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']
    

    因此,在这种情况下,您将在 celery.py 文件中导入模型,假设 __init.py__ 也是如此,您的模型将在 Django 加载其配置之前导入,而您的 settings.py 中的应用程序尚未构建。

    您不应该将 Django 应用程序的东西导入您的 __init__.py 文件,模块/应用程序是在 Django 加载配置(settings.py)之前构建的,这将引发错误 应用程序尚未加载 如果您尝试在__init__.py 文件中上传models 之类的内容。

    根据the documentation,Celery 拥有app.autodiscover_tasks() 能够发现在settings.INSTALLED_APPS 中任何注册良好的应用程序中找到的所有任务。无需在celery.py 中导入任务,只需在您的所有应用中创建一个tasks.py 文件即可。

    | projectname
    |____|__init__.py
    |____|celery.py # contains app.autodiscover_tasks()
    |____|settings.py
    |____|urls.py
    |____|wsgi.py
    |app1
    |____|tasks.py
    |app2
    |____|tasks.py
    

    任务可能在celery.py 文件中工作,但在从应用上传模型时不能工作,请改用 app.autodiscover_tasks()

    如果需要,也可以使用来自未来的绝对导入

    from __future__ import absolute_import
    

    【讨论】:

    • 昨晚,我做了这个,效果很好!感谢您的回答,也感谢您提供的详细信息,它可以帮助我了解问题所在。我应该很高兴解决这个问题,但我正在努力解决另一个问题(悲伤),而不是相关问题,也许我会问另一个问题,无论如何谢谢。这个答案很好,并且被接受了
    • 我不得不把自己置于同样的情况和同样的问题,以找出问题所在。很高兴它起作用了,正如你所说,我敢打赌我的问题一点也不棒,你是对的。(笑)
    • 问答都非常有帮助。节省了我的时间并解决了我的问题。干得好。
    猜你喜欢
    • 2017-02-02
    • 2017-07-04
    • 1970-01-01
    • 2021-12-20
    • 1970-01-01
    • 1970-01-01
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多