Django自定义中间件Middleware

    选择打赏方式

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',
]
版权声明:若无特殊注明,本文皆为《 张宇童 》原创,转载请保留文章出处。
本文链接:Django自定义中间件Middleware https://www.zyt8.cn/w/193.html
正文到此结束

热门推荐

发表吐槽

你肿么看?

你还可以输入 250 / 250 个字

嘻嘻 大笑 可怜 吃惊 害羞 调皮 鄙视 示爱 大哭 开心 偷笑 嘘 奸笑 委屈 抱抱 愤怒 思考 日了狗 胜利 不高兴 阴险 乖 酷 滑稽

评论信息框

吃奶的力气提交吐槽中...


既然没有吐槽,那就赶紧抢沙发吧!