【问题标题】:Websockets with Django Channels on HerokuHeroku 上带有 Django 通道的 Websockets
【发布时间】:2021-04-19 01:39:38
【问题描述】:

我正在尝试将我的应用程序部署到 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)

到这里:

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

这里是routing.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()),
]

这里是消费者.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,
        }))

这里是 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']

# 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 中的东西

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

【问题讨论】:

  • 嗨法比安。我有同样的问题。你是怎么解决的?
  • 嗨,保罗。这是答案stackoverflow.com/questions/65726281/…。长话短说:我必须将 heroku redis 添加为附加组件,然后获取创建附加组件后创建的 URI 值,并将该值放入 CHANNEL_LAYER/default/config/hosts 字典中。这可能有点令人困惑,我认为网络上对此没有很好的解释......祝你好运

标签: python django heroku websocket django-channels


【解决方案1】:

听起来您没有为您的项目正确设置 Procfile。由于 Channels 应用程序需要 HTTP/WebSocket 服务器和后端通道使用者,Procfile 需要定义这两种类型:

release: python manage.py migrate
web: daphne therapist_portal.asgi:application --port $PORT --bind 0.0.0.0
worker: python manage.py runworker channel_layer

完成初始部署后,您需要确保两种进程类型都在运行(Heroku 默认只会启动 web dyno,您也可以根据需要更改 dyno 层):

heroku ps:scale web=1:free worker=1:free

如果您仍然遇到问题,您可能需要将您的 asgy.py 文件更改为:

import os
import channels
import django

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "therapist_portal.settings")
django.setup()

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

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

这将确保 Daphne 能够正常启动。

注意 1:我假设您使用的是 Django 3.*Channels 3.*

注意 2:这个答案的一部分来自 Heroku 的 outdated docs

【讨论】:

    【解决方案2】:

    问题详情

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

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

    频道库

    快速入门

    您可以在Tutorial 阅读如何使用它。首先,按照安装和教程进行操作。

    在您的Procfile 中,您需要使用daphne,它默认与channels 库一起安装:

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

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

    在 heroku 环境 $PORT 替换为它提供的一些端口。您可以使用.env 文件在本地提供。

    您需要在room.htmlws:// 替换为wss://(请参阅错误和解决方案)。

    错误及解决办法

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

    • 确保通过settings (mysite.settings) 包含您的应用程序和频道,并使用asgi 应用程序:
    INSTALLED_APPS = [
        'channels',
        'chat',
        ...
    ]
    ...
    ASGI_APPLICATION = "mysite.asgi.application"
    
    • 确保使用通道层 (mysite.settings)。
    CHANNEL_LAYERS = {
        'default': {
            'BACKEND': 'channels.layers.InMemoryChannelLayer',
        },
    }
    

    根据Documentation,您应该使用数据库进行生产,但对于本地环境,您可以使用channels.layers.InMemoryChannelLayer

    • 确保您运行 asgi 服务器(不是 wsgi),因为您需要异步行为。此外,对于部署,您应该使用daphne 而不是gunicorndaphne 默认包含在 channels 库中,因此您无需手动安装。 基本运行服务器将如下所示(终端):
    daphne -b 0.0.0.0 -p $PORT mysite.asgi:application
    

    其中$PORT 是特定端口(对于 UNIX 系统是 5000)。 (heroku 应用使用的格式,你可以手动更改)。

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

    Difference between ws and wss?

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

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

    希望这个答案对channelsDjango 有用。

    【讨论】:

      【解决方案3】:

      如果您使用的频道 >=2,那么您不需要任何工人。您只需正确设置 Procfile 和设置。

      Procfile

      release: python manage.py migrate
      web: daphne <your-app>.asgi:application --port $PORT --bind 0.0.0.0 -v2
      

      settings.py

      ​​>
      CHANNEL_LAYERS = {
          "default": {
              "BACKEND": "channels_redis.core.RedisChannelLayer",
              "CONFIG": {
                  "hosts": [os.environ.get('REDIS_URL')],
              },
          },
      }
      

      请注意,我们在上面的主机中没有额外的6379 端口。

      【讨论】:

        猜你喜欢
        • 2018-11-24
        • 2021-09-17
        • 2021-11-16
        • 1970-01-01
        • 2015-08-13
        • 2022-01-25
        • 1970-01-01
        • 2012-02-21
        • 1970-01-01
        相关资源
        最近更新 更多