Closed 0716gzs closed 8 months ago
The error message django.core.exceptions.AppRegistryNotReady: Apps are not loaded yet
typically occurs in Django when Django's apps are not ready, often because of an attempt to import Django models before Django has been fully initialized. This usually happens when importing Django models outside of an appropriate context, such as at the module level in scripts that are not part of the standard Django workflow (like a standalone script or in this case, an MQTT client).
To resolve this issue in the context of your MQTT client script (mqtt.py
), you should consider the following steps:
Delay Importing Django Models: Instead of importing Django models at the top of your MQTT script, import them inside the function or method where they are needed. This ensures that these imports happen after Django has been fully initialized.
Ensure Django Setup: If the MQTT client script is a standalone script and not part of a Django management command, you need to explicitly set up Django. You can do this by adding the following lines at the beginning of your script, before importing any Django models:
import django
django.setup()
This should be done after setting the DJANGO_SETTINGS_MODULE
environment variable, which tells Django which settings to use.
Use Django Management Command: If possible, consider converting your MQTT client script into a Django management command. This is a more integrated way to run standalone scripts that require access to Django's features, including models. Django management commands are executed in the context of the Django project, ensuring all the necessary setup is done automatically.
Review Thread Safety: Since you're using threading in your MQTT client, make sure that your Django model operations are thread-safe. Django's ORM isn't inherently thread-safe, so you need to be cautious about accessing or modifying Django models from multiple threads.
By applying these changes, your MQTT client should be able to interact with Django models without encountering the AppRegistryNotReady
error. This will integrate MQTT functionalities smoothly within the Django framework.
If I process the models model while subscribing to mqtt, it will result in django. core. exceptions. AppRegistryNotReady: Apps are not loaded yet
源码 mqtt.py import paho.mqtt.client as mqtt from common.ProductData.BaseData import BaseProductData from .consumer import Consumer import threading
class MQTTClient: client = mqtt.Client(protocol=3) BROKER = 'broker' KEEPALIVE = 50 USER_NAME = 'root' PASSWORD = '123' PORT = 1883
client = MQTTClient() client.connect()
import json from common import const from common.views import RowDict from apps.product.models import Product, ProductUser, ProductAutomation from apps.scene.models import Scene from django.core.cache import cache
class ProductHandleClas: def init(self): pass
class SceneHandleClas: