11 Django实现WebSocket

  因为需要实时显示状态的需求,想到了websocket,但是Django原生不支持websocket,后来搜索到了chango-channels项目,可以实现次需求.

一、Channels

  官方文档

二、安装配置

  安装channels

pip install -U channels

  配置channels

  必须要在settings中进行配置才能使用channels。

1 #注册到app当中
2 INSTALLED_APPS = (
3     'django.contrib.auth',
4     'django.contrib.contenttypes',
5     'django.contrib.sessions',
6     'django.contrib.sites',
7     ...
8     'channels',
9 )

  设置channels的默认路由

1 from channels.routing import ProtocolTypeRouter
2 
3 application = ProtocolTypeRouter({
4     # 添加django视图中的路由(url.py中的路由)
5 })

  最后设置ASGI_APPLICATION,然后启动项目

ASGI_APPLICATION = "myproject.routing.application"

  因为channels要作用在项目的全局,最好把channels这个app放到INSTALLED_APPS的最上面。

  为了获取最新版的Channels要改变repo源,切换到项目虚拟环境中,进行安装

1 $ git clone [email protected]:django/channels.git
2 $ cd channels
3 $ <activate your project’s virtual environment>
4 (environment) $ pip install -e .  # the dot specifies the current repo

   一篇配合redis使用的channels:https://www.jianshu.com/p/3de90e457bb4

猜你喜欢

转载自www.cnblogs.com/a2534786642/p/11094869.html