码迷,mamicode.com
首页 > Web开发 > 详细

Django 3.x 原生支持websocket 配置

时间:2020-12-24 11:39:43      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:http   callable   web   nec   span   else   hat   rom   port   

{myproject}/websocket.py

 1 # websocket.py
 2 async def websocket_application(scope, receive, send):
 3     while True:
 4         event = await receive()
 5 
 6         if event[‘type‘] == ‘websocket.connect‘:
 7             await send({
 8                 ‘type‘: ‘websocket.accept‘
 9             })
10 
11         if event[‘type‘] == ‘websocket.disconnect‘:
12             break
13 
14         if event[‘type‘] == ‘websocket.receive‘:
15             if event[‘text‘] == ‘ping‘:
16                 await send({
17                     ‘type‘: ‘websocket.send‘,
18                     ‘text‘: ‘pong!‘
19                 })

{myproject}/asgi.py

 1 """
 2 ASGI config for chatroom project.
 3 
 4 It exposes the ASGI callable as a module-level variable named ``application``.
 5 
 6 For more information on this file, see
 7 https://docs.djangoproject.com/en/3.1/howto/deployment/asgi/
 8 """
 9 
10 import os
11 
12 from django.core.asgi import get_asgi_application
13 from chatroom.websocket import websocket_application
14 
15 os.environ.setdefault(‘DJANGO_SETTINGS_MODULE‘, ‘chatroom.settings‘)
16 
17 django_application = get_asgi_application()
18 
19 async def application(scope, receive, send):
20   if scope[‘type‘] == ‘http‘:
21     await django_application(scope, receive, send)
22   elif scope[‘type‘] == ‘websocket‘:
23     await websocket_application(scope, receive, send)
24   else:
25     raise NotImplementedError(f"Unknown scope type {scope[‘type‘]}")

 

Django 3.x 原生支持websocket 配置

标签:http   callable   web   nec   span   else   hat   rom   port   

原文地址:https://www.cnblogs.com/fengtao4918/p/14158114.html

踩
(0)
赞
(0)
   
举报
评论 一句话评论(0)
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!