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]')