django - 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
文件中,但那里也没有运气。我无法分辨我在做什么与频道文档不同,感谢您的帮助。
解决方案
尽早获取 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),
])
),
})
推荐阅读
- php - 带有 CURL 的 400 错误请求
- python - 请求:将数组拆分为多个同名参数?
- google-bigquery - 在 BigQuery 中查询 Google Analytics 事件:事件错误消息
- python - 在 3-D numpy 数组的小切片上有效地使用 1-D pyfftw
- primefaces - 为什么我的表单在渲染后没有重置他的样式?
- r - 使用 removeBimeraDenovo 函数时 R 控制台崩溃
- salesforce - 如何在流程构建器中引用多选选项列表字段值?
- r - aes_string(x = marketing_train$education, y = marketing_train$age) 中的错误:二元运算符的非数字参数
- c++ - 偶数和奇数位置元素之和之间的最大差异:如何记忆蛮力方法?
- apache-kafka - KafkaStream 的吞吐量低