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)
相关推荐
VW_4042 小时前
csdn-2026-11-23-第一站踩坑
爬虫·python
yiangL_3 小时前
课后作业4:基于 Python 的古诗词词云可视化(P205)
开发语言·python
Dmz丶3 小时前
前端转 AI 100 天 Day 52:RAG 项目实战(一)——从零搭建企业知识库
python
卷无止境7 小时前
用 SimPy 做离散事件仿真:时钟不走步,事件自己排队
后端·python
撸码猿7 小时前
数据采集场景的语序点选验证码:90.2% 整词准确率的本地 OCR 实践
python·ocr
用户0332126663678 小时前
使用 Python 在 Excel 中创建折线图和条形图
python·excel
木子欢儿9 小时前
Ubuntu 26.04 LTS 安装Python 3.12
linux·运维·服务器·python·ubuntu
Wellijohn9 小时前
Python 异步并发:我把 5 个坑踩完了,你照着抄模板就行
python
AI创界者9 小时前
Python 进阶实战(六十二章):分布式定时任务、异步工作流与幂等补偿机制实战
人工智能·python·aigc
炸薯条!11 小时前
Python面向对象基础:类与对象、实例方法、魔法方法和属性详解
java·开发语言·python