首页 > 其他分享 >26-中间件

26-中间件

时间:2023-03-24 18:11:28浏览次数:37  
标签:26 return process 中间件 request import response

# 1. 创建 .py模块 编写中间件
    import sys
    from django.http import HttpResponse
    from django.shortcuts import redirect
    from django.urls import reverse
    from django.utils.deprecation import MiddlewareMixin
    from django.views.debug import technical_500_response


    class MyMiddleware(MiddlewareMixin):
        # 访问路由时会先经过request中间件
        def process_request(self, request):  
            # 全局路由保护
            print(request.path)
            username = request.session.get('username')
            if username:
                return
            elif request.path != '/login/':  # 请求的不是登录页面
                return redirect("/login/")
        
        # 服务器返回时先经过response中间件
        def process_response(self, reqeust, response):  
            print("process_response")
            return response  # 必须返回响应对象


        # 在自己的试图函数之前执行
        def process_view(self, reqeust, view_func, view_args, view_kwargs):
            print("在自己的试图函数之前执行")

        
        # 错误页面处理 
        def process_exception(self, request, exception):
            print("exception")
            # 对管理员展示错误页面,一般用户只能看到404,500等页面
            ip = request.META.get("REMOTE_ADDR")
            if ip == '127.0.0.1':
                return technical_500_response(request, *sys.exc_info())
            return redirect(reverse("App02:index"))

  
# 2. settigs.py注册中间件
  MIDDLEWARE = [
    'App03.模块名.类名',
]

标签:26,return,process,中间件,request,import,response
From: https://www.cnblogs.com/kh-1314/p/17248426.html

相关文章