django3.0--ASGI

ASGI

简介

Django3 支持ASGI,可以实现异步通信(websocket)

按照daphne作为ASGI服务器

pip install daphne -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com

启动Daphne服务器

daphne <项目名>.asgi:application

asgi重写 判断是http请求还是socket请求

1.文件在项目根目录/asgi.py

async def application(scope, receive, send):
    # 判断是不是http请求
    if scope['type'] == 'http':
        await http_application(scope, receive, send)
    # 判断请求是不是websocket请求
    elif scope['type'] == 'websocket':
        await websocket_application(scope, receive, send)
    # 其他请求的话 就是报错
    else:
        raise Exception('unkown scope type, '+ scope['type'])

socket处理逻辑

import json

async def websocket_application(scope, receive, send):
    # 防止链接中断 要起一个循环
    while True:
        event = await receive()
        print('[event]', event)
        # 收到建立WebSocket链接请求
        if event['type'] == 'websocket.connect':
            await send({'type': 'websocket.accept'})
        # 收到中断WebSocket链接的消息
        elif event['type'] == 'websocket.disconnect':
            break
        elif event['type'] == 'websocket.receive':
            # 返回值采用json字符串进行返回
            data = [
                {
                    'id': 1,
                    'name': '小明'
                },
                {
                    'id': 2,
                    'name': '小红'
                }
            ]
            if event['text'] == 'ping':
                await send({
                    'type': 'websocket.send',
                    'text': json.dumps(data)
                })
        # 其他情况,正常的WebSocket消息
        else:
            pass
    print('[disconnect]')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值