使用asgi时,尚未加载Django应用

时间:2018-12-08 15:07:58

标签: django django-channels asgi

我正在尝试使用asgi而不是wsgi来运行django项目。我已经按照以下步骤设置了routing.py和asgi.py:

routing.py

from django.conf.urls import url
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator, 
OriginValidator
from channels.auth import AuthMiddlewareStack

from some.consumers import SomeConsumer


application = ProtocolTypeRouter({
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [
                    url(r'^some_url/$', SomeConsumer),
                ]
            )
         )
    )
})

asgi.py

import os
from channels.routing import get_default_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
application = get_default_application()

现在,您可以看到它是标准设置,并且可以在默认的django服务器上正常运行,但是当我尝试与其他(daphne或uvicorn)服务器一起运行时,会抛出此异常。

这是我的INSTALLED_APPS

INSTALLED_APPS = [
    'channels',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.sites',
    'django_jenkins',
    'easy_thumbnails',
    'image_cropping',
    'allauth',
    'allauth.account',
    'and_rest_of_my_own_apps',
]

有人有这样的问题吗?

----编辑----

这是一个堆栈跟踪:

Traceback (most recent call last):

File "/path/to/my/env/bin/daphne", line 11, in <module>
    sys.exit(CommandLineInterface.entrypoint())
  File "/path/to/my/env/lib/python3.6/site-packages/daphne/cli.py", line 161, in entrypoint
    cls().run(sys.argv[1:])
  File "/path/to/my/env/lib/python3.6/site-packages/daphne/cli.py", line 222, in run
    application = import_by_path(args.application)
  File "/path/to/my/env/lib/python3.6/site-packages/daphne/utils.py", line 12, in import_by_path
    target = importlib.import_module(module_path)
  File "/path/to/my/env/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./my_project/asgi.py", line 5, in <module>
    application = get_default_application()
  File "/path/to/my/env/lib/python3.6/site-packages/channels/routing.py", line 33, in get_default_application
    module = importlib.import_module(path)
  File "/path/to/my/env/lib/python3.6/importlib/__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 994, in _gcd_import
  File "<frozen importlib._bootstrap>", line 971, in _find_and_load
  File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 665, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 678, in exec_module
  File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
  File "./my_project/routing.py", line 4, in <module>
    from channels.auth import AuthMiddlewareStack
  File "/path/to/my/env/lib/python3.6/site-packages/channels/auth.py", line 12, in <module>
    from django.contrib.auth.models import AnonymousUser
  File "/path/to/my/env/lib/python3.6/site-packages/django/contrib/auth/models.py", line 2, in <module>
    from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
  File "/path/to/my/env/lib/python3.6/site-packages/django/contrib/auth/base_user.py", line 47, in <module>
    class AbstractBaseUser(models.Model):
  File "/path/to/my/env/lib/python3.6/site-packages/django/db/models/base.py", line 100, in __new__
    app_config = apps.get_containing_app_config(module)
  File "/path/to/my/env/lib/python3.6/site-packages/django/apps/registry.py", line 244, in get_containing_app_config
    self.check_apps_ready()
  File "/path/to/my/env/lib/python3.6/site-packages/django/apps/registry.py", line 127, in check_apps_ready
    raise AppRegistryNotReady("Apps aren't loaded yet.")
django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet.

和命令

daphne -b 0.0.0.0 -p 8000 my_project.asgi:application --access-log=./logs/daphne-access.log

3 个答案:

答案 0 :(得分:3)

对于使用Django> 3.0的任何人,请参考下面的链接。对我有用

https://www.gitmemory.com/issue/django/channels/1564/722354397

您要做的就是在导入其他任何内容之前先致电get_asgi_application()

答案 1 :(得分:1)

事实证明,Channels 库中的 django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet 错误是由于我的应用程序中无效的导入顺序而发生的 - 如 here 所述。

原因:

在导入我的 WSAccessTokenAuthMiddleware 实例之前,我先导入了我的 django_asgi_app

解决方案:

django_asgi_app 之前导入我的 WSAccessTokenAuthMiddleware 解决了问题。

# First, import app created by get_asgi_application() - django.core.asgi
from general.settings.asgi import application as django_asgi_app

# Second, import my middleware and consumers
from general.consumers import ModelConsumer
from general.util.auth import WSAccessTokenAuthMiddleware

# Third, Import channels classes
from django.conf.urls import url
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter
from channels.routing import URLRouter


application = ProtocolTypeRouter({
    "http": django_asgi_app,
    'websocket': WSAccessTokenAuthMiddleware(
        AuthMiddlewareStack(
            URLRouter([
                url('ws/models/(?P<model_name>\w+)', ModelConsumer.as_asgi()),
            ])
        )
    )
})

答案 2 :(得分:0)

在独立应用程序中使用Django基础结构之前,应始终执行django.setup()

因此,您的asgi.py应该像

import os
from channels.routing import get_default_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
django.setup()
application = get_default_application()