首页 > Web开发 > 详细

Django 3.x 原生支持websocket 配置

时间:2020-12-19 12:16:49      阅读:84      评论:0      收藏:0      [点我收藏+]

{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 配置

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!