欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python3之Django Web框架中间件

程序员文章站 2022-07-03 23:23:36
...

中间件的使用:

主要用来处理页面的登录校验、跨站请求伪造防御、日志记录、session设置,权限管理等

具体代码:

class MiddlewareMixin(object):
    def __init__(self, get_response=None):
        self.get_response = get_response
        super(MiddlewareMixin, self).__init__()

    def __call__(self, request):
        response = None
        if hasattr(self, 'process_request'):
            response = self.process_request(request)
        if not response:
            response = self.get_response(request)
        if hasattr(self, 'process_response'):
            response = self.process_response(request, response)
        return response


class DealLoginMiddleware(MiddlewareMixin):
    def process_request(self, request):
        if request.path_info == '/crm/login/':
            return None
        if not request.session.get('user_info'):
            return redirect('/crm/login/')

    def process_response(self, request, response):
        return response

还要在settings中注册一下:

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',
#注册下自定义中间件
'middleware.controller.DealLoginMiddleware'

]