Django 3.x 原生支持websocket 配置

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

上一篇:React中JSX的理解


下一篇:js面试题--new的原理