django中间件,中间件给下面传值

1、新建middleware.py文件

复制代码
# myapp/middleware.py
import time
from django.http import HttpRequest
import json
from django.http import JsonResponse
import urllib.parse
class RequestTimeMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request: HttpRequest):
        # 记录请求开始时间
        start_time = time.time()
        # 调用下一个中间件或视图
        response = self.get_response(request)
        # 计算请求处理时间
        process_time = time.time() - start_time
        # 打印处理时间
        print(f"访问地址:{request.path},时间:{process_time:.4f}")

        json_data = json.loads(request.body.decode('utf-8'))
        # 获取请求头中的 User 和 Token,请求中中文乱码,使用urllib转码
        user = urllib.parse.unquote(request.META.get('HTTP_USER'))
        token = urllib.parse.unquote(request.META.get('HTTP_TOKEN'))
        if request.path == "/app/login":
            return response
        else:
            data = {
                "code": "20001",
                "data": json_data,
                "message": "不合法"
            }
            return JsonResponse(data)

2、注册中间件settings.py

复制代码
'middleware.middleware.RequestTimeMiddleware', #中间件

3、中间件给下面传值

复制代码
 # 给 request 对象添加自定义属性,给路由加值,下面方法使用type = request.user_type获得
request.user_type = list[0]['type']
response = self.get_response(request)

完整代码

复制代码
# myapp/middleware.py
import time
from django.http import HttpRequest
import json
from django.http import JsonResponse
import urllib.parse
from django.core.cache import cache
from comm.Db import Db
class RequestTimeMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request: HttpRequest):
        # 记录请求开始时间
        # start_time = time.time()
        # 调用下一个中间件或视图
        response = self.get_response(request)
        # 计算请求处理时间
        # process_time = time.time() - start_time
        # 打印处理时间
        # print(f"访问地址:{request.path},时间:{process_time:.4f}")

        # 获取请求头中的 User 和 Token,请求中中文乱码,使用urllib转码
        user = urllib.parse.unquote(request.META.get('HTTP_USER'))
        token = urllib.parse.unquote(request.META.get('HTTP_TOKEN'))
        if request.path == "/app/login":
            return response
        else:
            # 判断redis的token,和请求头的token是否相等,相等放行
            value = cache.get(f"{user}")
            if value == token:
                db = Db()
                list = db.query(f"select * from wb_admin where user='{user}'")
                if len(list) < 1:
                    data = {
                        "code": "2006",
                        "data": [],
                        "message": "账号不存在"
                    }
                    return JsonResponse(data)
                # 给 request 对象添加自定义属性,给路由加值,下面方法使用type = request.user_type获得
                request.user_type = list[0]['type']
                response = self.get_response(request)
                return response

            # 获得post请求参数
            json_data = json.loads(request.body.decode('utf-8'))
            data = {
                "code": "2001",
                "data": json_data,
                "message": "没有权限访问"
            }
            return JsonResponse(data)

# 代理管理
# 必备引入
import json
from django.views.decorators.http import require_POST, require_http_methods
from django.http import JsonResponse
# 其它引入

# 查询接口
@require_http_methods(["POST"])
def select(request):
    json_data = json.loads(request.body.decode('utf-8'))
    type = request.user_type
    print(type)
    data = {
        "code": "2000",
        "data": json_data,
        "message": "登录成功"
    }
    return JsonResponse(data)
相关推荐
Jackilina_Stone1 小时前
【模型量化】GPTQ 与 AutoGPTQ
人工智能·python·gptq
橙色小博3 小时前
PyTorch中的各种损失函数的详细解析与通俗理解!
人工智能·pytorch·python·深度学习·神经网络·机器学习
小森77673 小时前
(三)机器学习---线性回归及其Python实现
人工智能·python·算法·机器学习·回归·线性回归
-XWB-3 小时前
【LLM】使用MySQL MCP Server让大模型轻松操作本地数据库
人工智能·python·自然语言处理
PacosonSWJTU4 小时前
python基础-13-处理excel电子表格
开发语言·python·excel
小军要奋进5 小时前
httpx模块的使用
笔记·爬虫·python·学习·httpx
Johnny_Cheung5 小时前
字符串、列表、元组、字典
开发语言·python
独行soc5 小时前
2025年渗透测试面试题总结- 某四字大厂面试复盘扩展 一面(题目+回答)
java·数据库·python·安全·面试·职场和发展·汽车
梦回阑珊6 小时前
《QT从基础到进阶·七十四》Qt+C++开发一个python编译器,能够编写,运行python程序改进版
c++·python·qt
前端开发张小七6 小时前
13.Python Socket服务端开发指南
前端·python