【问题标题】:Why does django-channels not connect to secure Websockets wss?为什么 django-channels 不连接到安全的 Websockets wss?
【发布时间】:2021-04-19 21:40:41
【问题描述】:

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

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

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

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

这就是错误发生的地方:由于某种原因,asgi.py 文件或 routing.py 文件无法将 websocket 连接到 consumer.py 中的正确使用者

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

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

这些都没有改变错误甚至错误消息。

报错信息总是抱怨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()),
    
]

这里是消费者.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 或 consumer.py 文件之一不能与 wss WebSockets 一起使用。

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

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

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

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

如果您能帮我解决这个问题,或者您是否可以向我指出以前遇到此问题的人的方向,请告诉我。

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

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

【问题讨论】:

  • 你可以尝试在“0.0.0.0”而不是“127.0.0.1”上运行它我在使用flask socket io stackoverflow.com/questions/51920267/…时遇到了问题@只是一个尝试
  • 您的意思是使用 runserver 命令?什么命令 python manage.py runserver 0.0.0.0 不起作用
  • 在允许的主机中,你有“127.0.0.1”可能会尝试用“0.0.0.0”替换
  • 嗯,不走运。将其添加到允许的主机,但 python manage.py runsenserver 仍连接到 127.0.0.1。
  • 当我运行 python manage.py runserver 0.0.0.0:8000 我得到一个错误......

标签: python django websocket django-channels asgi


【解决方案1】:

我能够通过一些更改在 localhost 上进行连接。在此更改之前,它甚至对 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 代码。

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

【讨论】:

  • 谢谢安东!这对于测试和 Heroku 非常有用,但我在频道文档中阅读了不要将 InMemoryChannelLayer 用于生产。我应该用什么来生产???
  • 你需要为heroku启用redis并为其获取连接字符串并将其放入settings.py中
  • 这是你的意思吗? ` CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("redis://:p83d12345c9a9b171d9c0b954aa60a2b15bef62e6ae30e06877a1e9bc8794b13@ec2-501---6 compute-1.amazonaws.com:27039", 27039)], }, }, } ` 我在 Heroku Redis 附加组件设置文件夹中的附加组件中找到了这些凭据 这里仍然有问题,因为它仍然没有连接...
  • 没关系!我想到了! CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": *** heroku-redis URI 与结尾的端口号一样 }, } , } 并且没有端口作为第二个参数 => 根本没有第二个参数我希望这可以节省很多时间!谢谢安东!你是超级英雄……如果我们在现实生活中相遇,我肯定欠你一杯啤酒
  • 谢谢)也许有一天会喝啤酒,祝你好运)
猜你喜欢
  • 1970-01-01
  • 2020-03-04
  • 2015-06-04
  • 2018-04-06
  • 1970-01-01
  • 2014-07-06
  • 2022-01-12
  • 2019-05-03
  • 2021-11-09
相关资源
最近更新 更多