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)
相关推荐
源码之家38 分钟前
计算机毕业设计:Python汽车销量数据采集分析可视化系统 Flask框架 requests爬虫 可视化 车辆 大数据 机器学习 hadoop(建议收藏)✅
大数据·爬虫·python·django·flask·课程设计·美食
Roselind_Yi43 分钟前
【吴恩达2026 Agentic AI】面试向+项目实战(含面试题+项目案例)-2
人工智能·python·机器学习·面试·职场和发展·langchain·agent
2401_8274999943 分钟前
python核心语法01-数据存储与运算
java·数据结构·python
一直会游泳的小猫44 分钟前
ClaudeCode完整学习指南
python·ai编程·claude code·claude code指南
第一程序员44 分钟前
Python与容器化:Docker和Kubernetes实战
python·github
JaydenAI1 小时前
[RAG在LangChain中的实现-04]常用的向量存储和基于向量存储的检索器
python·langchain·ai编程
Roselind_Yi1 小时前
【吴恩达2026 Agentic AI】面试向+项目实战(含面试题+项目案例)-1
人工智能·python·面试·职场和发展·langchain·gpt-3·agent
Alan GEO实施教练1 小时前
专利申请是否找代理机构:核心考量与决策逻辑拆解
大数据·人工智能·python
oyguyteggytrrwwwrt1 小时前
抄写YOLOE源码——先抄写ultralytics包,关于__init__.py
开发语言·python
berryyan1 小时前
🚀 Windows + RTX 5090 + ComfyUI 桌面版 安装 SageAttention 完全手册
人工智能·python