Django Tenant throwing raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path) error

I am working on a Django project that uses Django Channels, Daphne, and Django Tenants for multitenancy and WebSocket communication. My project structure includes a project folder and several application folders.

In the project folder, I have the usual files like asgi.py, wsgi.py, settings.py, and consumers.py (for handling Django Channels). I am not using routing.py. In the application folder, I have files like models.py, serializers.py, views.py, and urls.py.

The WebSocket communication works fine, but I encounter an issue when trying to import a service module in consumers.py.

asgi.py

import os
from django.core.asgi import get_asgi_application
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.urls import path, re_path
from .consumers import ABConsumer
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'autobiz.settings')
import django
django.setup()
# 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()

application = ProtocolTypeRouter({
    "http": django_asgi_app,
    # Just HTTP for now. (We can add other protocols later.).
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter([
                #path("ws/admin/", ABConsumer.as_asgi()),
                re_path(r'ws/server/(?P<tenant_name>\w+)/$', ABConsumer.as_asgi()),
            ])
        )
    ),
})

consumers.py

from channels.generic.websocket import AsyncWebsocketConsumer
import json
import logging
**from autobiz.abshared.services import process_token
**
# Setting up logging
logger = logging.getLogger(__name__)


class ABConsumer(AsyncWebsocketConsumer):

    async def connect(self):
        # Get tenant name from the URL
        self.tenant_name = self.scope['url_route']['kwargs']['tenant_name']  # Extract tenant name from URL route
        self.room_name = f'{self.tenant_name}_room'  # Create a tenant-specific room name
        self.room_group_name = f'chat_{self.room_name}'

        logger.info(f"Connection attempt from tenant: {self.tenant_name}")

        # Join the tenant-specific room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )

        # Accept the WebSocket connection
        await self.accept()

    async def receive(self, text_data=None, bytes_data=None):
        # Handle incoming message (text or binary)
        if text_data:
            logger.info(f"Received text data from tenant {self.tenant_name}: {text_data}")
            response = {
                'tenant': self.tenant_name,
                'message': f'{text_data}'
            }

            # Perform the import inside the method to avoid circular import issues

            # Send the message to the room group (broadcast to all clients in the room)
            await self.channel_layer.group_send(
                self.room_group_name,
                {
                    'type': 'chat_message',
                    'message': json.dumps(response)  # Convert response to JSON
                }
            )
        elif bytes_data:
            logger.info(f"Received binary data from tenant {self.tenant_name}.")
            await self.send(bytes_data=b'Server received binary data')

    async def chat_message(self, event):
        # Send the broadcast message back to WebSocket clients
        message = event['message']

        # Send the message to the WebSocket connection
        await self.send(text_data=message)

    async def disconnect(self, close_code):
        # Leave the tenant-specific room group when the socket closes
        logger.info(f"Disconnected from tenant {self.tenant_name} with code: {close_code}")

        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

In my settings.py ASGI setting is:

ASGI_APPLICATION = 'autobiz.asgi.application'

After running the ASGI server, everything works fine until I add this line to consumers.py:

from autobiz.abshared.services import process_token

When I add the import statement, I get the following error:

 raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'autobiz.asgi'

  • autobiz is my project name.
  • abshared is my app name.
  • services.py is located inside the abshared app. What I've Tried: Downgrading Django, Channels, and Redis-Channels versions. Adding import django; django.setup() in asgi.py. Verifying the default environment settings. Ensuring the path to the services.py file is correct. None of these solutions have worked, and the issue persists. It seems that Django is not finding the correct path for the services.py file, while other imports work just fine.

Expectation: I expect Django to properly resolve the path to the services.py file in the same way other imports are working. Any suggestions on how to fix this error would be greatly appreciated!

Вернуться на верх