为什么 django-channels 不连接到安全的 Websockets wss?

Why does django-channels not connect to secure Websockets wss?

最近我一直在开发一个名为(DBSF - don’t be a sh***y friend)的应用程序,它的功能有点像 facebook,但它会提醒你偶尔与朋友互动. 遇到一个BUG,很久都无法修复

该应用程序在我的本地计算机上运行良好,但是当我尝试将应用程序部署到 heroku 时,我 运行 遇到了一个错误。

问题是关于使用 Websockets 和 Django-channels 的用户之间的聊天功能。 这是由 heroku 需要 https 引起的,因此 websockets 也必须是安全的(wss:// 而不是 ws://)。

所以我这样做了,我创建了一个安全的 webSocket,其中 url 以 wss://

开头

这里是错误发生的地方:由于某些原因 asgi.py 文件无法建立连接,或者 routing.py 文件无法将 websocket 连接到 consumers.py

以下是我尝试修复错误的方法:

  1. 在 asgi.py 我将 http 更改为 https,或将 websocket 更改为其中之一(websockets,ws wss)
  2. 更改了 settings.py
  3. 中的安全设置
  4. 尝试了 websocket 的不同组合 url
  5. 运行用 daphne 代替 Django 的开发服务器

None 其中更改了错误甚至错误消息。

报错信息总是抱怨socket还在连接或者已经关闭或者处于关闭状态

这是一些代码

在浏览器上(为了在我的本地机器上重新创建错误,我只是硬编码 'wss'):

var ws_scheme = window.location.protocol == "https:" ? "wss" : "ws";
      const chatSocket = new WebSocket(
        ws_scheme
        + '://'
        + window.location.host
        + '/ws/chat/'
        + friendship_id
        + '/'
      );

这里是asgi.py

import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "DBSF.settings")

import django
django.setup()

from django.core.management import call_command


from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
import social.routing

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DBSF.settings')

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            social.routing.websocket_urlpatterns
        )
    ),
})

这里是routing.py

from django.urls import re_path, path
from . import consumers

websocket_urlpatterns = [
    re_path(r'ws/chat/(?P<friendship_id>\w+)/$', consumers.ChatConsumer.as_asgi()),
    
]

这里是consumers.py

import json
from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from .models import Message, Friendship, User
import datetime

class ChatConsumer(WebsocketConsumer):
   
    def connect(self):
        print('fuuuuuuuu')
        self.room_name = self.scope['url_route']['kwargs']['friendship_id']
        self.room_group_name = 'chat_%s' % self.room_name
        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )

    # Receive message from WebSocket
    def receive(self, text_data):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        sender = text_data_json['sender']
        receiver = text_data_json['receiver']
        friendship_id = self.scope['url_route']['kwargs']['friendship_id']
        message_to_save = Message(conversation=Friendship.objects.get(id=friendship_id), sender=User.objects.get(username=sender), receiver=User.objects.get(username=receiver), text=message, date_sent=datetime.datetime.now())
        message_to_save.save()

        # Send message to room group
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message,
                'sender': sender,
                'receiver': receiver,
                'id': message_to_save.id
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']
        sender = event['sender']
        receiver = event['receiver']
        id = event['id']

        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message,
            'sender': sender,
            'receiver': receiver,
            'id': id,
        }))

这里是settings.py:

"""
Django settings for DBSF project.

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

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

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

from pathlib import Path
import django_heroku
import os
from dotenv import load_dotenv
load_dotenv()
# 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/3.1/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = os.environ['SECRET_KEY']
AUTH_USER_MODEL = 'social.User'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['desolate-lowlands-74512.herokuapp.com', 'localhost', '127.0.0.1']
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
SECURE_HSTS_SECONDS = 3600
SECURE_SSL_REDIRECT = False
SESSION_COOKIE_SECURE = False
CSRF_COOKIE_SECURE = False
# Application definition

INSTALLED_APPS = [
    'channels',
    'social',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'whitenoise.middleware.WhiteNoiseMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

ROOT_URLCONF = 'DBSF.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',
            ],
        },
    },
]

REST_FRAMEWORK = {
    # Use Django's standard `django.contrib.auth` permissions,
    # or allow read-only access for unauthenticated users.
    'DEFAULT_PERMISSION_CLASSES': [
        'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
    ]
}

WSGI_APPLICATION = 'DBSF.wsgi.application'
ASGI_APPLICATION = 'DBSF.asgi.application'
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('https://desolate-lowlands-74512.herokuapp.com/', 6379)],
        },
    },
}

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

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


# Password validation
# https://docs.djangoproject.com/en/3.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/3.1/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'EST'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATIC_URL = '/static/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media/')
MEDIA_URL= "/media/"



错误信息如下:

layout.js:108 WebSocket connection to 'wss://desolate-lowlands-74512.herokuapp.com/ws/chat/19/' failed: Error during WebSocket handshake: Unexpected response code: 500

这是完整的项目: https://github.com/fabianomobono/DBSF

这是 heroku 上的应用程序: https://desolate-lowlands-74512.herokuapp.com/

基本上,asgi.py、routing.py 或 consumers.py 文件之一不能与 wss WebSockets 一起工作。

当我在本地机器上使用普通的 webSocket(ws) 时,该应用程序可以正常工作。

我真的认为这是一个很容易解决的问题,但我已经尝试了几个星期了。

这是一个小错误还是我试图解决这个问题的方式完全错误?

这可能是 django-channels 的错误吗??

请让我知道您是否能够帮助我解决这个问题,或者您是否可以指出以前遇到过此问题的人的方向。

如果我对这个错误的解释足够好,或者我不清楚我在问什么,请告诉我。

有人知道如何解决这个问题吗?

我可以通过一些更改连接到本地主机。在此更改之前,它甚至不适用于 ws:// 协议。所以我的改变:

  1. 你确定你设置了正确的redis吗?为了测试你可以试试
CHANNEL_LAYERS = {
    'default': {
        "BACKEND": "channels.layers.InMemoryChannelLayer"
    },
}
  1. 在 github 的代码中,你的路线有错误,它是:
   re_path(r'wss/chat/(?P<friendship_id>\w+)/$', consumers.ChatConsumer.as_asgi()),

但应该是

    re_path(r'ws/chat/(?P<friendship_id>\w+)/$', consumers.ChatConsumer.as_asgi()),

根据您的 javascript 代码。

祝你好运,希望对你有所帮助。