栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

django2 channels配置

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

django2 channels配置

1、安装指定版本的包
pip install channels==3.0.4

pip install channels_redis

2.settings里配置

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

]

WSGI_APPLICATION = 'Dating_Sofware.wsgi.application'    #Dating_Sofware项目名称
ASGI_APPLICATION = "Dating_Sofware.asgi.application"

CHANNEL_LAYERS = {
    'default': {
        'BACKEND': 'channels_redis.core.RedisChannelLayer',
        'CONFIG': {
            "hosts": [('127.0.0.1', 6379)],
        },
    },
}

3.在项目根目录下创建asgi.py内容如下:
import os
import django
from channels.http import AsgiHandler
from channels.routing import ProtocolTypeRouter, URLRouter
from . import routings      # 这个文件后续会说,你先写上。

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Dating_Sofware.settings')#Dating_Sofware 是项目名称
django.setup()
application = ProtocolTypeRouter(
    {
        "http": AsgiHandler(),     # http走Django默认的asgi
        "websocket": URLRouter(routings.websocket_urlpatterns),         # websocket走channels
    }
)
4.同根目录下创建consumers.py内容如下:
import json

from asgiref.sync import async_to_sync
from channels.generic.websocket import WebsocketConsumer
from channels.exceptions import StopConsumer

CONN_LIST = []


class ChatConsumer(WebsocketConsumer):
    def websocket_connect(self, message):
        print("开始链接...")
        # 有客户端来向后端发送websocket连接的请求时,自动触发。
        # 服务端允许和客户端创建连接(握手)。
        self.accept()
        CONN_LIST.append(self)



    def websocket_receive(self, message):
        print('22222222', message)
        data = json.loads(message.get('text', '{}'))
        chat_type = data.get('chat_type')
        chat_id = data.get('chat_id')
        chat_content = data.get('message')
        if chat_type == 'add_chat':
            async_to_sync(self.channel_layer.group_add)(chat_id, self.channel_name)
        else:
            async_to_sync(self.channel_layer.group_send)(chat_id, {"type": 'chat.message', 'message': message})




    def chat_message(self, event):
        self.send(event['message']['text'])

    def websocket_disconnect(self, message):
        CONN_LIST.remove(self)
        raise StopConsumer()
5.项目根目录下创建routings.py
from django.urls import path
from Dating_Sofware.consumers import ChatConsumer #Dating_Sofware是创建的项目名。consumers是上面创建的consumers.py

websocket_urlpatterns = [
    path('ws/chat', ChatConsumer.as_asgi()),
]

6.运行项目出现如下内容即可
Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
June 22, 2022 - 19:19:44
Django version 2.2.2, using settings 'Dating_Sofware.settings'
Starting ASGI/Channels version 3.0.4 development server at http://127.0.0.1:8000/ 出现ASGI算完成
Quit the server with CTRL-BREAK.

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/983118.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号