Channels 3 Daphne Uvicorn Error AppRegistryNotReady

Django 在使用 Channels 3 時,使用 Daphne 或者 Uvicorn 啓動會出現 AppRegistryNotReady 錯誤

這個主要的原因是在項目啓動前未初始化,我嘗試自行解決了一下

如果你的 asgi.py 是如下形式

"""
ASGI config for homados project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""

import os

from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application
from homados.middleware.wsmw import QueryXTokenAuthMiddleware
from channels.routing import ProtocolTypeRouter, URLRouter
import apps.duplex.routing
import apps.synergy.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'homados.settings.dev_micro')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    # Just HTTP for now. (We can add other protocols later.)
    'websocket': QueryXTokenAuthMiddleware(
        URLRouter(
            apps.duplex.routing.websocket_urlpatterns +
            apps.synergy.routing.websocket_urlpatterns
        )
    ),
})

那麼應該是會報另外一個錯誤,在項目設置 DJANGO_SETTINGS_MODULE 前調用settings,這個錯誤只需要把設置環境變量前提即可

但是前提後還是會有 AppRegistryNotReady 的錯誤,這個錯誤查詢了一下,這個Issue 已經提出瞭解決方案,原因是因爲django還未初始化時調用了channels路由註冊,可以通過下面形式的代碼來解決

"""
ASGI config for homados project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""

import os

from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter


os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'homados.settings.dev_micro')

django_asgi_app = get_asgi_application()


from homados.middleware.wsmw import QueryXTokenAuthMiddleware
import apps.duplex.routing
import apps.synergy.routing

application = ProtocolTypeRouter({
    "http": django_asgi_app,
    # Just HTTP for now. (We can add other protocols later.)
    'websocket': QueryXTokenAuthMiddleware(
        URLRouter(
            # msf 執行結果推送
            apps.duplex.routing.websocket_urlpatterns +
            # 聊天室
            apps.synergy.routing.websocket_urlpatterns
        )
    ),
})

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章