0
点赞
收藏
分享

微信扫一扫

16.CSS菜单悬停特效

青青子衿谈育儿 2023-09-01 阅读 65

django ASGI/Channels 启动和 ASGI/daphne的区别 

文件类比

daphne 启动命令

python本身只支持http协议 使用websocket需要下载第三方库

  需要在seting.py里配置,将我们的channels加入INSTALLED_APP里。

尾行添加

修改asgi.py文件

在settings.py的同级目录创建routing.py 

在web.views中创建consumers.py 

django中需要了解的

  • wsgi,只支持http请求
  • asgi,wsgi+异步+websockt

settings.py的installed_apps中的首行

简单使用前端页面测试websocket

当前问题不管高版本还是低版本 老是报如下问题

之后找到老师获取课程中的源代码 笔者使用教程中的代码跑通了

还是回到这个问题

这个坑废了我2天时间

ValueError: No application configured for scope type 'websocket'

经过课程中的代码和笔者的代码来回对比 多次测试

这里应该是websocket 而缺少了e字母 应该是写项目的时候复制csdn参考源码 网友留的坑

 而后将项目依赖全部升级为最新版本 完全可以跑通!

 效果图

小结

基于django实现websocket请求 但只能对某个人进行处理

群聊(二)

基于channels中提供channel layers来实现。

  • setting中配置。

    CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer",
        }
    }
    pip3 install channels-redis
    CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels_redis.core.RedisChannelLayer",
            "CONFIG": {
                "hosts": [('10.211.55.25', 6379)]
            },
        },
    }
  • consumers中特殊的代码。

    from channels.generic.websocket import WebsocketConsumer
    from channels.exceptions import StopConsumer
    from asgiref.sync import async_to_sync
    ​
    ​
    class ChatConsumer(WebsocketConsumer):
        def websocket_connect(self, message):
            # 接收这个客户端的连接
            self.accept()
    ​
            # 获取群号,获取路由匹配中的
            group = self.scope['url_route']['kwargs'].get("group")
    ​
            # 将这个客户端的连接对象加入到某个地方(内存 or redis)
            async_to_sync(self.channel_layer.group_add)(group, self.channel_name)
    ​
        def websocket_receive(self, message):
            group = self.scope['url_route']['kwargs'].get("group")
    ​
            # 通知组内的所有客户端,执行 xx_oo 方法,在此方法中自己可以去定义任意的功能。
            async_to_sync(self.channel_layer.group_send)(group, {"type": "xx.oo", 'message': message})
    ​
        def xx_oo(self, event):
            text = event['message']['text']
            self.send(text)
    ​
        def websocket_disconnect(self, message):
            group = self.scope['url_route']['kwargs'].get("group")
    ​
            async_to_sync(self.channel_layer.group_discard)(group, self.channel_name)
            raise StopConsumer()
    ​

总结

b站演示地址 ​ https://b23.tv/UZvBFy3 ​

  • websocket是什么?协议。

  • django中实现websocket,channels组件。

    • 单独连接和收发数据。

    • 手动创建列表 & channel layers。

【全网最详细Django的websocket 通信原理,聊天室,实战案例-哔哩哔哩】http://​ https://b23.tv/os2enKj ​

参考链接http://t.csdn.cn/RyrcC

备用链接django中配置websocket_基于wsgi创建的项目怎么实现websocket_qq_36606793的博客-CSDN博客

举报

相关推荐

0 条评论