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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值