django 尝试使用通道运行到服务器时出错

voase2hg  于 2023-03-09  发布在  Go
关注(0)|答案(1)|浏览(105)

我在运行python manage.py runserver时遇到了问题,为了更好地举例说明,请参见我的代码,其灵感来自于 Django 3 by Example 一书。
settings.py

"""
Django settings for educa project.

Generated by 'django-admin startproject' using Django 4.1.

For more information on this file, see
https://docs.djangoproject.com/en/4.1/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/4.1/ref/settings/
"""

from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'XXX'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = []

# Application definition

INSTALLED_APPS = [
    'channels',
    'courses.apps.CoursesConfig',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'students.apps.StudentsConfig',
    'embed_video',
    'debug_toolbar',
    'redisboard',
    'chat.apps.ChatConfig', 
]

MIDDLEWARE = [
    'debug_toolbar.middleware.DebugToolbarMiddleware',
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    # 'django.middleware.cache.UpdateCacheMiddleware',
    'django.middleware.common.CommonMiddleware',
    # 'django.middleware.cache.FetchFromCacheMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'educa.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]
ASGI_APPLICATION = 'educa.routing.application'
WSGI_APPLICATION = 'educa.wsgi.application'

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': BASE_DIR / 'db.sqlite3',
    }
}

# Password validation
# https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]

# Internationalization
# https://docs.djangoproject.com/en/4.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_TZ = True

# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.1/howto/static-files/

STATIC_URL = 'static/'

MEDIA_URL = 'media/'
MEDIA_ROOT = BASE_DIR / 'media'

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'

from django.urls import reverse_lazy
LOGIN_REDIRECT_URL = reverse_lazy('student_course_list')

'''CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.redis.RedisCache',
        'LOCATION': 'redis://127.0.0.1:6379',
    }
}

CACHE_MIDDLEWARE_ALIAS = 'default'
CACHE_MIDDLEWARE_SECONDS = 60 * 15  # 15 minutes
CACHE_MIDDLEWARE_KEY_PREFIX = 'educa'

INTERNAL_IPS = [
    '127.0.0.1',
]
'''

project/urls.py

from django.contrib import admin
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.auth import views as auth_views
from courses.views import CourseListView

urlpatterns = [
    path('accounts/login/', auth_views.LoginView.as_view(),
          name='login'),
    path('accounts/logout/', auth_views.LogoutView.as_view(),
          name='logout'),
    path('admin/', admin.site.urls),
    path('course/', include('courses.urls')),
    path('', CourseListView.as_view(), name='course_list'),
    path('students/', include('students.urls')),
    path('__debug__/', include('debug_toolbar.urls')),
    path('chat/', include('chat.urls', namespace='chat')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL,
                          document_root=settings.MEDIA_ROOT)

chat/views.py

from django.shortcuts import render, get_object_or_404
from django.http import HttpResponseForbidden
from django.contrib.auth.decorators import login_required

@login_required
def course_chat_room(request, course_id):
    try:
        # retrieve course  with given id joined by the current user
        course = request.user.courses_joined.get(id=course_id)
    except:
        # user is not a student of the course or course does not exist
        return HttpResponseForbidden()
    return render(request, 'chat/room.html', {'course': course})

chat/urls.py

from django.urls import path
from . import views

app_name = 'chat'

urlpatterns = [
 path('room/<int:course_id>/', views.course_chat_room,
 name='course_chat_room'),
]

chat/consumers.py

import json
from channels.generic.websocket import AsyncWebsocketConsumer
from asgiref.sync import async_to_sync
from django.utils import timezone

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.user = self.scope['user']
        self.id = self.scope['url_route']['kwargs']['course_id']
        self.room_group_name = 'chat_%s' % self.id
        # join room group
        await self.channel_layer.group_add(
            self.room_group_name,
            self.channel_name
        )
        # accept connection
        await self.accept()

    async def disconnect(self, close_code):
        # leave room group
        await self.channel_layer.group_discard(
            self.room_group_name,
            self.channel_name
        )

    # receive message from WebSocket
    async def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        now = timezone.now()

        # send message to room group
        await self.channel_layer.group_send(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'user': self.user.username,
                'datetime': now.isoformat(),
            }
        )

    # receive message from room group
    async def chat_message(self, event):
        # send message to WebSocket
        await self.send(text_data=json.dumps(event))

chat/routing.py

from django.urls import re_path
from . import consumers

websocket_urlpatterns = [
 re_path(r'ws/chat/room/(?P<course_id>\d+)/$', consumers.
ChatConsumer),
]

project/routing.py

from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import chat.routing

application = ProtocolTypeRouter({
    'websocket': AuthMiddlewareStack(
        URLRouter(
            chat.routing.websocket_urlpatterns
        )
    ),
})

ERROR

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
October 27, 2022 - 15:50:38
Django version 4.1.2, using settings 'educa.settings'
Starting ASGI/Channels version 2.4.0 development server at http://127.0.0.1:8000/
Quit the server with CTRL-BREAK.
Exception in thread django-main-thread:
Traceback (most recent call last):
  File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\routing.py", line 29, in get_default_application
    module = importlib.import_module(path)
  File "C:\Users\Sagittarius Infiny A\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module
    return _bootstrap._gcd_import(name[level:], package, level)
  File "<frozen importlib._bootstrap>", line 1050, in _gcd_import
  File "<frozen importlib._bootstrap>", line 1027, in _find_and_load
  File "<frozen importlib._bootstrap>", line 1006, in _find_and_load_unlocked
  File "<frozen importlib._bootstrap>", line 688, in _load_unlocked
  File "<frozen importlib._bootstrap_external>", line 883, in exec_module
  File "<frozen importlib._bootstrap>", line 241, in _call_with_frames_removed
  File "C:\Users\Sagittarius Infiny A\Desktop\educa2\educa\routing.py", line 1, in <module>
    from channels.auth import AuthMiddlewareStack
  File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\auth.py", line 15, in <module>
    from django.utils.translation import LANGUAGE_SESSION_KEY
ImportError: cannot import name 'LANGUAGE_SESSION_KEY' from 'django.utils.translation' (C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\django\utils\translation\__init__.py)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Users\Sagittarius Infiny A\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner 
    self.run()
  File "C:\Users\Sagittarius Infiny A\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run
    self._target(*self._args, **self._kwargs)
  File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper     
    fn(*args, **kwargs)
  File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\management\commands\runserver.py", line 101, in inner_run
    application=self.get_application(options),
  File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\management\commands\runserver.py", line 126, in get_application
    return StaticFilesWrapper(get_default_application())
  File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\routing.py", line 31, in get_default_application
    raise ImproperlyConfigured("Cannot import ASGI_APPLICATION module %r" % path)
django.core.exceptions.ImproperlyConfigured: Cannot import ASGI_APPLICATION module 'educa.routing'

当尝试交互式模块并尝试从 * 项目的 * routing.py导入 * 应用程序 * 时,出现此错误。

$ python manage.py shell
>> from educa.routing import application
Traceback (most recent call last):  File "<console>", line 1, in <module>
  File "C:\Users\Sagittarius Infiny A\Desktop\educa2\educa\routing.py", line 1, in <module>
    from channels.auth import AuthMiddlewareStack
  File "C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\channels\auth.py", line 15, in <module>
    from django.utils.translation import LANGUAGE_SESSION_KEY
ImportError: cannot import name 'LANGUAGE_SESSION_KEY' from 'django.utils.translation' (C:\Users\Sagittarius Infiny A\Desktop\educa2\env\lib\site-packages\django\utils\translation\__init__.py)
9udxz4iz

9udxz4iz1#

卸载通道包,然后安装通道包,它的作品为我....

相关问题