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)
相关推荐
晓风残月淡1 小时前
JVM字节码与类的加载(二):类加载器
jvm·python·php
西柚小萌新4 小时前
【深入浅出PyTorch】--上采样+下采样
人工智能·pytorch·python
shut up6 小时前
LangChain - 如何使用阿里云百炼平台的Qwen-plus模型构建一个桌面文件查询AI助手 - 超详细
人工智能·python·langchain·智能体
宝贝儿好6 小时前
【python】第五章:python-GUI编程
python·pyqt
闲人编程7 小时前
从多个数据源(CSV, Excel, SQL)自动整合数据
python·mysql·数据分析·csv·存储·数据源·codecapsule
B站_计算机毕业设计之家7 小时前
推荐系统实战:python新能源汽车智能推荐(两种协同过滤+Django 全栈项目 源码)计算机专业✅
大数据·python·django·汽车·推荐系统·新能源·新能源汽车
茯苓gao7 小时前
Django网站开发记录(一)配置Mniconda,Python虚拟环境,配置Django
后端·python·django
Full Stack Developme8 小时前
Python Redis 教程
开发语言·redis·python
码界筑梦坊8 小时前
267-基于Django的携程酒店数据分析推荐系统
python·数据分析·django·毕业设计·echarts
Cherry Zack8 小时前
Django视图进阶:快捷函数、装饰器与请求响应
后端·python·django