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)
相关推荐
biuyyyxxx5 分钟前
Python自动化办公学习笔记(一) 工具安装&教程
笔记·python·学习·自动化
极客数模17 分钟前
【2026美赛赛题初步翻译F题】2026_ICM_Problem_F
大数据·c语言·python·数学建模·matlab
小鸡吃米…2 小时前
机器学习中的代价函数
人工智能·python·机器学习
Li emily3 小时前
如何通过外汇API平台快速实现实时数据接入?
开发语言·python·api·fastapi·美股
m0_561359673 小时前
掌握Python魔法方法(Magic Methods)
jvm·数据库·python
Ulyanov3 小时前
顶层设计——单脉冲雷达仿真器的灵魂蓝图
python·算法·pyside·仿真系统·单脉冲
2401_838472514 小时前
使用Python进行图像识别:CNN卷积神经网络实战
jvm·数据库·python
CoLiuRs4 小时前
语义搜索系统原理与实现
redis·python·向量·es
zhihuaba4 小时前
使用PyTorch构建你的第一个神经网络
jvm·数据库·python
u0109272714 小时前
Python Web爬虫入门:使用Requests和BeautifulSoup
jvm·数据库·python