20

I'm tring to run my django project with usage of asgi instead of wsgi. I have set up my routing.py and asgi.py as follows:

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()

Now, as you can see it's standard setup and it works fine with default django server but when I try to run with some other (daphne or uvicorn) it's throwning this exception.

Here is my 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',
]

Has anyone had problem like this?

---- EDIT ----

Here is a stacktrace:

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.

and command

daphne -b 0.0.0.0 -p 8000 my_project.asgi:application --access-log=./logs/daphne-access.log
kebie
  • 485
  • 5
  • 16

3 Answers3

47

For anyone using Django > 3.0 refer to link below. It worked for me

https://github.com/django/channels/issues/1564#issuecomment-722354397

all you have to do is to call get_asgi_application() before importing anything else

Sample of my asgi.py file:

import os

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

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

from django.conf import settings
from .routing import asgi_routes

asgi_routes["http"] = django_asgi_app
application = ProtocolTypeRouter(asgi_routes)
Klaas van Schelven
  • 2,374
  • 1
  • 21
  • 35
Arash77
  • 613
  • 1
  • 5
  • 7
  • I followed the suggestion of the OP there and called `django.setup()` before every other imports. I also had to pass the `--preload` flag to gunicorn. – chidimo Mar 01 '21 at 16:11
  • 3
    Hi @Arash thank you so much for taking the time to post this for versions after 3.0! Really appreciate it because you saved me a TON of time, i never would have figured that out – Tom Mar 27 '21 at 05:15
  • 2
    thank you so much, saved me a lot of headaches – Samuele B. May 05 '21 at 09:39
12

Before using Django infrastructure in standalone application you should always do django.setup()

So, your asgi.py should be like

import os
from channels.routing import get_default_application

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "my_project.settings")
django.setup()
application = get_default_application()
mingaleg
  • 2,017
  • 16
  • 28
  • Thanks, it worked. But could you explain what standalone application exactly means? Because I run my whole project so I woudn't call it standalone application. – kebie Dec 08 '18 at 23:40
  • Please follow this link: https://docs.djangoproject.com/en/2.1/topics/settings/#calling-django-setup-is-required-for-standalone-django-usage – mingaleg Dec 08 '18 at 23:44
  • 2
    Well, the link says 'Note that calling django.setup() is only necessary if your code is truly standalone. When invoked by your Web server, or through django-admin, Django will handle this for you.' Isn't it invoked by web server in my situation? – kebie Dec 09 '18 at 00:27
  • @kebie is true, on this part 'Note that calling django.setup() is only necessary if your code is truly standalone. – Pranta chakraborty Nov 30 '22 at 18:01
  • after adding django.setup() I getting the same error yet. – Sajib Hossain Jan 09 '23 at 19:42
5

It turned out that django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet error in Channels lib, happened due to invalid import order in my application - as explained here.

Cause:

I imported my WSAccessTokenAuthMiddleware before importing my instance of django_asgi_app.

Solution:

Importing my django_asgi_app before WSAccessTokenAuthMiddleware fixed the problem.

# 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()),
            ])
        )
    )
})
Lukasz Dynowski
  • 11,169
  • 9
  • 81
  • 124