Django3.0 ASGI Websocket Package

Github

Gitea

安装包

pip install djangowebsocket

更改项目下 asgi.py 文件

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'})
视图的 request 中有以下属性
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

By ahri

遇到问题请到 github 或 gitea 提交 Issues

你可能感兴趣的:(python,django,websocket)