关于python:Django30-ASGI-Websocket-Package

88次阅读

共计 1350 个字符,预计需要花费 4 分钟才能阅读完成。

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

正文完
 0