dev_task icon indicating copy to clipboard operation
dev_task copied to clipboard

django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

Open zhangjinzhi opened this issue 5 years ago • 1 comments

环境: 以下两种环境都会报出该错误: 1. Ubuntu16、Python2.7.12 2. Ubuntu16、Python3.5 其余模块版本按作者的进行安装。

报错信息:

xxxx/packages/django/apps/registry.py", line 124, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

终于找到了官方文档中关于报错问题:

https://docs.djangoproject.com/en/1.10/ref/applications/#app-loading-process

解决方法:参考官方文档

1. Initialization process
1.1 How applications are loaded
关键点:
When Django starts, django.setup() is responsible for populating the application registry.

2. Troubleshooting
解释了可能引发错误的场景

代码中如何解决:

@shared_task
def exec_command_or_script(task_name, host, cmd):

改为:

import django
django.setup()

@shared_task
def exec_command_or_script(task_name, host, cmd):

且celery.py文件中

app.autodiscover_tasks()
# app.autodiscover_tasks(force=True) 设置为true,会导致报错,

最终:

tasks.py文件中的任务,写到celery.py文件中,加上django.setup()即可


## 这两行必须在task.models前,不然无法自动找到setting文件
import django
django.setup()

# from supply.email_send import send_monitor_email
from task.models import TimedTask
from celery import shared_task
from dev_task import settings
import subprocess

@shared_task
def exec_command_or_script(task_name, host, cmd):
    timetask_obj = TimedTask.objects.get(name=task_name)

    if str(host) == str(settings.host_ip):

        try:

参考的讨论帖:

https://stackoverflow.com/questions/34114427/django-upgrading-to-1-9-error-appregistrynotready-apps-arent-loaded-yet(重要)

https://github.com/celery/celery/issues/3584(重要)

https://docs.djangoproject.com/en/1.10/ref/applications/#initialization-process

https://stackoverflow.com/questions/52557060/python3-exception-using-shared-task-with-queue-option

http://docs.celeryproject.org/en/latest/userguide/tasks.html

http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html

zhangjinzhi avatar Jan 17 '19 01:01 zhangjinzhi