作者:Yyao | 来源:互联网 | 2023-10-12 18:09
GithubGitea安装包pipinstalldjangowebsocket更改我的项目下asgi.py文件importosfromdjango.core.asgiimportg
文章目录[隐藏] - Github
- Gitea
- 安装包
- 更改我的项目下 asgi.py 文件
- 视图类
- 中间件类
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