首页 > 解决方案 > Django Channels ASGI - AppRegistryNotReady:应用程序尚未加载

问题描述

使用通道 asgi 开发服务器运行我的项目python manage.py runserver可以完美地启动它,但是当使用 Daphne ( daphne project.routing:application) 运行项目时,我得到了错误AppRegistryNotReady: Apps aren't loaded yet

settings.py

INSTALLED_APPS = [
    'channels',
    'whitenoise.runserver_nostatic',
    'django.contrib.staticfiles',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.sites',
    # ...
    # ... installed apps and custom apps
]

WSGI_APPLICATION = 'project.wsgi.application'

ASGI_APPLICATION = 'project.routing.application'

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [REDIS_URL],
        }
    },
}

routing.py

import os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter

from django.core.asgi import get_asgi_application
from django.conf.urls import url

from my_app.consumers import MyCustomConsumer

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    'websocket': AuthMiddlewareStack(
        URLRouter([
            url(r'^ws/custom/$', MyCustomConsumer),
        ])
    ),
})

我已经尝试django.setup()按照其他问题中的描述添加,以及使用uvicorn而不是运行,daphne但仍然出现相同的错误。我也尝试过指向 websocket 路由settings.CHANNEL_LAYERS['ROUTING']并将应用程序初始化移出到一个asgi.py文件中,但那里也没有运气。我无法分辨我在做什么与频道文档不同,感谢您的帮助。

标签: djangodjango-channelsdaphneuvicornasgi

解决方案


尽早获取 Django ASGI 应用程序,以确保在导入可能导入 ORM 模型的消费者和 AuthMiddlewareStack 之前填充 AppRegistry。

import os
from django.conf.urls import url
from django.core.asgi import get_asgi_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "project.settings")
django_asgi_app = get_asgi_application()

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter

from my_app.consumers import MyConsumer

application = ProtocolTypeRouter({
# Django's ASGI application to handle traditional HTTP requests
"http": django_asgi_app,
# WebSocket chat handler
"websocket": AuthMiddlewareStack(
    URLRouter([
        path('ws/custom/', MyConsumer),
    ])
),

})


推荐阅读