Django Tenant бросает ошибку raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)

Я работаю над проектом Django, который использует Django Channels, Daphne и Django Tenants для многопользовательского доступа и WebSocket-коммуникаций. Структура моего проекта включает папку проекта и несколько папок приложений.

В папке проекта у меня есть обычные файлы, такие как asgi.py, wsgi.py, settings.py и consumers.py (для работы с каналами Django). Я не использую routing.py. В папке приложения у меня есть такие файлы, как models.py, serializers.py, views.py и urls.py.

Взаимодействие через WebSocket работает нормально, но при попытке импортировать модуль сервиса в 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
        )

В моем файле settings.py ASGI настроен следующим образом:

ASGI_APPLICATION = 'autobiz.asgi.application'

После запуска ASGI-сервера все работает нормально, пока я не добавлю эту строку в consumers.py:

from autobiz.abshared.services import process_token

Когда я добавляю оператор импорта, я получаю следующую ошибку:

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

  • autobiz - название моего проекта.
  • abshared - имя моего приложения.
  • services.py находится внутри приложения abshared. Что я пробовал: Понизить версии Django, Channels и Redis-Channels. Добавление импорта django; django.setup() в asgi.py. Проверка настроек окружения по умолчанию. Убедиться в правильности пути к файлу services.py. Ни одно из этих решений не помогло, и проблема сохраняется. Похоже, что Django не находит правильный путь к файлу services.py, в то время как другие импорты работают нормально.

Ожидания: Я ожидаю, что Django правильно определит путь к файлу services.py так же, как работают другие импорты. Любые предложения о том, как исправить эту ошибку, будут очень признательны!

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