Django 3.x 原生支持websocket 配置

2020-12-24 19:28

阅读:774

标签: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


评论


亲,登录后才可以留言!