pip install djangowebsocket
python
import os from django.core.asgi import get_asgi_application from djangowebsocket import get_ws_application from djangowebsocket import path, paths, middleware os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Project.settings') http_application = get_asgi_application() websocket_application = get_ws_application() # 注册路由,彻底匹配,后续将支持正则 path('/path1/', ViewClass1) # ViewClass 视图类 # 或 paths({ '/path2/': ViewClass2, '/path3/': ViewClass3, }) # 注册中间件,有顺序的 middleware(MiddlewareClass1) # MiddlewareClass1 中间件类 # 或(1.0.0不可用) middlewares([MiddlewareClass2, MiddlewareClass3]) # http、websocker请求分发 async def branch(scope, receive, send): if scope.get('type') == 'websocket': await websocket_application(scope, receive, send) else: await http_application(scope, receive, send) application = branch
from djangowebsocket import BaseWebSocketView, Response class WebSocketView(BaseWebSocketView): def websocket(self, request): # Response's data can be str, dict, list, tuple, etc. return Response({'test': '123'})
QUERY # params in path HEADER TYPE ASGI SCHEM SERVER CLIENT ROOT_PATH PATH RAW_PATH SUB_PROTOCOLS
from djangowebsocket import BaseMiddleware class MD(BaseMiddleware): def process_request(self, request): print(request.data) # Preprocess request return request def process_response(self, request, response): response.set_data({'111': 222}) # 经过 set_data 方法设置数据 return response