Third-party module of websocket

In practical applications, not all back-end frameworks support the websocket protocol by default. If you want to use it, you may need to use different third-party modules.

"""
后端框架
django
	默认不支持websocket
	第三方模块:channels

flask
	默认不支持websocket
	第三方模块:geventwebsocket
	
tornado
	默认支持websocket
"""

How does django support websocket

# 下载channels模块需要注意的点
# 1.版本不要用最新版 推荐使用2.3版本即可 如果你安装最新版可能会出现自动将你本地的django版本升级为最新版
# 2.python解释器建议使用3.6版本(3.5可能会有问题,3.7可能会有问题 具体说明问题没有给解释)
pip3 install channels==2.3
"""channels模块内部帮你封装了握手/加密/解密等所有操作"""

Basic use

  • Register app

    INSTALLED_APPS = [
        'channels'
    ]
    

    After the registration is completed, django will not start and will directly report an error

    CommandError: You have not set ASGI_APPLICATION, which is needed to run the server.

  • Configuration

    # 2 配置变量
    ASGI_APPLICATION = 'day01.routing.application'
    ASGI_APPLICATION = '项目名同名的文件名.文件夹下py文件名默认就叫routing.该py文件内部的变量名默认就叫application'
    
  • Go to the folder with the same project name and create a new py file to define the application variable

    from channels.routing import ProtocolTypeRouter,URLRouter
    
    
    application = ProtocolTypeRouter({
        'websocket':URLRouter([
            # 书写websocket路由与视图函数对应关系
        ])
    })
    

After the above operation configuration is completed, starting Django will start from the original wsgiref to asgi startup (internal: Daphne)

And after starting, django supports both websocket and http protocol

The operation based on http is still done in urls.py and views.py

Operations based on websocket are done in routing.py and consumer.py (created in the corresponding application)

Guess you like

Origin www.cnblogs.com/yafeng666/p/12691991.html