Django自定义中间件Middleware

2019-11-5 张宇童 Python

from django.utils.deprecation import MiddlewareMixin
# from django.http import HttpResponse
from django.shortcuts import HttpResponse, redirect
 
 
# 方式一:
class MyMiddleware(MiddlewareMixin):
    def process_request(self, request):
        next_url = request.path_info
        if not request.path_info.startswith("/login/"):
            # 做登录验证
            login_flag = request.session.get("login", "")
            if not login_flag:
                return redirect("/login/?next={}".format(next_url))
 
    def process_view(self, request, view_func, view_args, view_kwargs):
        pass
 
    def process_exception(self, request, exception):
        if isinstance(exception, ValueError):
            return HttpResponse("404")
 
    def process_response(self, request, response):
        return response # 这里必须返回response
 
 
# 方式二:
class SimpleMiddleware(object):
    def __init__(self, get_response):
        self.get_response = get_response
        # 一次性配置和初始化。
 
    def __call__(self, request):
        # Code to be executed for each request before
        # the view (and later middleware) are called.
        # 这里写的代码会在视图被调用前执行来处理请求
        response = self.get_response(request)
        # 这里写的代码会在视图调用后执行来处理响应
        # Code to be executed for each request/response after
        # the view is called.
 
        return response
 
    def process_view(self, request, view_func, view_args, view_kwargs):
        pass
 
    def process_exception(self, request, exception):
        pass
 
    def process_template_response(self, request, response):
	pass

# 在settings.py里的下面列表中添加自定义的中间件来激活该中间件
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'mymiddlewares.middlewares.MyMiddleware',
    'mymiddlewares.middlewares.SimpleMiddleware',
]

标签: python3 中间件

评论(0) 浏览(587)

Powered by emlog