Heroku 上带有 Django Channels 的 Websocket

2024-04-23

我正在尝试将我的应用程序部署到heroku。 该应用程序有一个简单的聊天系统,使用 Websockets 和 django 通道。

当我使用 python manage.py runserver 测试我的应用程序时,应用程序的行为正如预期的那样。

我尝试部署该应用程序,除了聊天系统之外,所有功能都可以使用。

这是我在 Chrome 控制台中收到的错误消息:

layout.js:108 Mixed Content: The page at 'https://desolate-lowlands-74512.herokuapp.com/index' was loaded over HTTPS, but attempted to connect to the insecure WebSocket endpoint 'ws://desolate-lowlands-74512.herokuapp.com/ws/chat/19/'. This request has been blocked; this endpoint must be available over WSS.

这就是我试图解决的问题:我从 ws 转到 wss 我改变了这个:

 const chatSocket = new WebSocket(
        'ws://'
        + window.location.host
        + '/ws/chat/'
        + friendship_id
        + '/'
      );
      console.log(chatSocket)

to this:

 const chatSocket = new WebSocket(
        'wss://'
        + window.location.host
        + '/ws/chat/'
        + friendship_id
        + '/'
      );
      console.log(chatSocket)

进行此更改后,Websocket 会加载,但聊天系统仍然无法工作。 消息仍未发送或接收

这是我打开聊天框时收到的错误消息:

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

这是我尝试发送消息时收到的错误消息:

WebSocket is already in CLOSING or CLOSED state.

这是代码: 这是我的 asgi.py 文件:

"""
ASGI config for DBSF project.

It exposes the ASGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
"""

import os

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
        )
    ),
})

这是路由.py

from django.urls import re_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):
        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,
        }))

这是设置.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']

# 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": [('127.0.0.1', 6379)],
        },
    },
}

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

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


# 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/"

这是 wsgi.py

"""
WSGI config for DBSF project.

It exposes the WSGI callable as a module-level variable named ``application``.

For more information on this file, see
https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/
"""

import os

from django.core.wsgi import get_wsgi_application

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

application = get_wsgi_application()

我假设一旦我从 ws 更改为 wss ,消费者就无法连接。我认为这将是一个简单的修复,但我不知道我需要更改哪些代码。我怀疑是asgy.py或routing.py中的东西

如果不清楚我要问什么或者我是否需要显示任何其他文件,请告诉我


问题详情

您好,这是我自己发现的一些部署类似的步骤mysiteHeroku 服务器的应用程序。我使用了这个库:

django==3.2.6
channels==3.0.4
python==3.9.6

频道库

快速开始

您可以阅读如何使用它Tutorial https://channels.readthedocs.io/en/stable/tutorial/index.html。首先,按照安装和教程进行操作。

In your Procfile你需要使用daphne https://github.com/django/daphne安装有channels https://github.com/django/channels默认库:

web: daphne -b 0.0.0.0 -p $PORT mysite.asgi:application

如果您使用最新版本的频道,则不需要任何工作人员。

在heroku环境中$PORT替换为它提供的一些端口。您可以使用以下方式在本地提供它.env file.

最后需要更换的东西ws:// with wss://(请参阅错误和解决方案)位于room.html.

错误及解决方案

意外的响应代码:200(或其他代码XXX)(已解决):

  • 请务必通过以下方式提供您的申请和渠道settings (mysite.settings)并使用asgi应用:
INSTALLED_APPS = [
    'channels',
    'chat',
    ...
]
...
ASGI_APPLICATION = "mysite.asgi.application"
  • 确保使用通道层(mysite.settings).
CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels.layers.InMemoryChannelLayer',
    },
}

根据文档 https://channels.readthedocs.io/en/stable/topics/channel_layers.html#in-memory-channel-layer您应该在生产中使用数据库,但对于本地环境,您可以使用channels.layers.InMemoryChannelLayer.

  • 一定要跑asgi服务器(不wsgi)因为你需要异步行为。另外,对于部署,您应该使用daphne https://github.com/django/daphne代替gunicorn. daphne https://github.com/django/daphne包含在channels https://github.com/django/channels默认库,因此您无需手动安装。 基本运行服务器将如下所示(终端):
daphne -b 0.0.0.0 -p $PORT mysite.asgi:application

where $PORT是特定端口(对于UNIX系统是5000)。 (用于heroku应用程序的格式,您可以手动更改它)。

连接建立时出错:net::ERR_SSL_PROTOCOL_ERROR 和使用 https 连接时出现相同错误(已解决):

ws 和 wss 之间的区别? https://stackoverflow.com/questions/46557485/difference-between-ws-and-wss

您可能会考虑通过 wss 协议使用您的服务器: 代替ws://... with wss://...或在您的 html 中使用以下模板(chat/templates/chat/room.html):

(window.location.protocol === 'https:' ? 'wss' : 'ws') + '://'

希望这个答案对您有用channels with Django.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Heroku 上带有 Django Channels 的 Websocket 的相关文章

随机推荐

  • io.cucumber 和 info.cukes 之间有什么区别

    我正在尝试使用 Cucumber 集成 BDD 但我真的很困惑有什么区别io 黄瓜 and 信息库克斯图书馆 以及使用哪一种以及何时使用 我尝试阅读并理解 github自述文件 md https github com cucumber cu
  • 如何清理提交树中未使用的侧分支?

    如何清理提交树中未使用的侧分支 不是真正的 git 分支 示例 树 假提交哈希 提交消息 可选 指针 0001 last commit master origin master HEAD 0002 old unused merge 0003
  • 使用 Jquery 验证插件 Ajax 远程验证 WordPress 用户名和电子邮件

    有谁知道如何使用 jquery 验证插件验证 WordPress 用户名和电子邮件 我正在尝试使用验证的远程方法检查用户名和电子邮件是否存在 我注意到 WordPress 有 username exists 和 email exists 等
  • Java关闭PDF错误

    我有这个java代码 try PDFTextStripper pdfs new PDFTextStripper String textOfPDF pdfs getText PDDocument load doc doc add new Fi
  • 禁用 UITextfield 的键盘

    我想知道如何禁用 UITextfield 的输入视图 环境textField inputView nil or textField setInputView nil 在 ShouldBeginEditing 中不执行任何操作 并使用user
  • [NSObject:任何对象]?' Xcode 6 Beta 6 中没有名为“下标”的成员

    我正在 Swift 中的 Xcode 6 Beta 6 中构建一个应用程序 但我不断收到此错误 NSObject AnyObject does not have a member named subscript 我不知道如何解决这个问题 我
  • 生成ip和限时下载链接

    有一个用于下载文件的直接链接 用户可以在付款后下载该链接 如下所示 http example com download webapp rar 但我需要生成ip和时间限制的下载链接 以防止其他人窃取该文件 我想在不使用任何数据库的情况下执行此
  • 在哪里将 google-services.json 文件放入 eclipse 项目中?

    我正在尝试实施新的GCM client在安卓上 在某一时刻 您必须启用Google Services对于该应用程序 启用后Cloud Messaging你必须下载该文件google services json并将其放入app or mobi
  • 模块化和抽象反应组件功能

    我下面有一个工作组件 允许所有复选框和复选框 它工作完美 然而 我讨厌这样的想法 每次我想使用此功能时 我都必须携带所有这些代码 我正在寻找一种在反应中使这个模块化的方法 这是 它不会将 输入检查所有 功能的整个功能模块化在一处 我必须在每
  • 如何在 svn 存储库中搜索任何修订版中是否存在文件

    如何搜索名为foo txt曾经提交到我的 svn 存储库 在任何修订版中 右键单击签出文件夹的根目录 gt TortoiseSVN gt 显示日志 您也可以在那里输入文件名
  • 如何用C语言播放MP3文件?

    我正在寻找在 C 中播放 MP3 文件的最简单方法 我正在寻找一个库 在其中我可以只调用文件名上的函数 或者一个将运行并退出的可执行文件 请建议 Using FMOD http www fmod org download 跨平台 这应该像这
  • 通过 ServiceStack api 使用 Linq2Twitter 和缓存的 OAuth 令牌

    我想使用 Linq2Twitter 从 ServiceStack 编写的 REST API 中进行 Twitter API 调用 我有以下信息 消费者钥匙 消费者秘密 当用户在网站上验证我们的应用程序时缓存的 OAuth 令牌 当用户在网站
  • 使用 F# 进行循环与递归

    这里的示例代码解决了一个项目欧拉问题 从数字 1 开始 按顺时针方向向右移动 方向 5 x 5 螺旋形成如下 21 22 23 24 25 20 7 8 9 10 19 6 1 2 11 18 5 4 3 12 17 16 15 14 13
  • 有没有办法使用 perf 工具查找流程中各个功能的性能?

    我正在尝试在流程中实现各个功能的性能 我该如何使用 perf 工具来做到这一点 还有其他工具吗 例如 假设 main 函数调用函数 A B C 我想分别获得主要功能以及功能 A B C 的性能 有没有一个很好的文档来了解 perf 源代码
  • Tomcat 上的 Grails - 如何记录原始 HTTP 请求/响应

    我找不到配置我的虚拟教程 Grails 应用程序来记录 Grails 服务器 实际上是 Tomcat 接受 生成的所有 HTTP 请求和响应的方法 这可能吗 另一种选择是使用 tomcat 的内置访问日志记录 http tomcat apa
  • 如何首先使用 msbuild 构建依赖项目

    我刚刚开始研究 msbuild 因为我想制作自己的构建脚本 目前 我可以创建仅编译一个项目的构建脚本 但如何处理依赖项 例如 如果我有两个使用这两个 msbuild 脚本构建的项目怎么办 项目A xml 项目B xml 如何告诉 msbui
  • 用于构建“调试”和“发布”JAR 文件的惯用 Gradle 脚本

    我正在尝试创建一个 Gradle 构建脚本来构建 Java jar文件处于 发布 或 调试 模式 并且在参数化脚本时遇到问题 问题是 使用 Java 插件在 Gradle 脚本中执行此操作的惯用方法是什么 或者 如果没有惯用的方法 那么真正
  • FCM flutter 启用通知振动

    我正在为 Android 和 IOS 开发 Flutter 应用程序 我已经根据这个为Android创建了通知渠道article https rechor medium com creating notification channels
  • 类型 x 比值更难访问

    这是我的代码的抽象 module RootModule module private SubModule I want everything in this module to be inaccessible from outside th
  • Heroku 上带有 Django Channels 的 Websocket

    我正在尝试将我的应用程序部署到heroku 该应用程序有一个简单的聊天系统 使用 Websockets 和 django 通道 当我使用 python manage py runserver 测试我的应用程序时 应用程序的行为正如预期的那样