'"Cannot import ASGI_APPLICATION module %r" % path channels problem

I got this error: ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)

Here is my routing.py:

from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from channels.auth import AuthMiddlewareStack
from django.urls import path

from messanger.contacts.consumers import ChatConsumer

application = ProtocolTypeRouter({
    # Empty for now (http->django views is added by default)
    'websocket': AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                [
                    path('user-notification', ChatConsumer)
                ]
            )
        )
    )
})

When i remove this line of code, runserver work: from messanger.contacts.consumers import ChatConsumer

But i don't understand what's wrong with my consumers file in contacts app:

from channels.consumer import AsyncConsumer


class ChatConsumer(AsyncConsumer):

    async def websocket_connect(self, event):
        await self.send({
            "type": "websocket.accept",
        })

    async def websocket_receive(self, event):
        await self.send({
            "type": "websocket.send",
            "text": event["text"],
        })



Solution 1:[1]

In your settings.py file add:

ASGI_APPLICATION = 'yourappname.asgi.application'

Solution 2:[2]

I was able to solve this issue by going in the asgi.py file and import get_asgi_application() which act as tradition http request fallback Like so in asgi.py :

mport os

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
from django.urls import path

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "mysite.settings")
# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()

from chat.consumers import AdminChatConsumer, PublicChatConsumer

application = ProtocolTypeRouter({
    # Django's ASGI application to handle traditional HTTP requests
    "http": django_asgi_app,

    # WebSocket chat handler
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter([
                path("chat/admin/", AdminChatConsumer.as_asgi()),
                path("chat/", PublicChatConsumer.as_asgi()),
            ])
        )
    ),
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Panagiotis Simakis
Solution 2 Godda