不忘初心,
牢记使命。

Django基础中间件---django请求生命周期、自定义中间件、中间件登录认证白名单

2021-04-05 大聪明 2评论 345 1喜欢

中间件介绍

# MIDDLEWARE就是中间件

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',
]

django请求生命周期(重点)

img

自定义中间件

中间件顾名思义,是介于request与response处理之间的一道处理过程,相对比较轻量级,并且在全局上改变django的输入与输出。

from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse

class MD1(MiddlewareMixin):

    def process_request(self, request):  # 必须定义这个名字的方法,参数必须写的
        print('MD1请求来了')
        print(request.path)  # 请求路径
        if request.path == '/xx/':
            return None
        else:
            return HttpResponse('你有问题,不让你走了!')  # 后边的都不走了
        # return None # 逻辑正常运行完了  不行默认就是return None

    def process_response(self, request, response):  # 必须定义这个名字的方法,两个参数也是必须写的
        print('MD1响应来了')
        return response  # 必须返回response


class MD2(MiddlewareMixin):

    def process_request(self, request):  # 必须定义这个方法
        print('MD2请求来了')

    def process_response(self, request, response):
        print('MD2响应来了')
        return response
# settins文件中配置
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',
    # 自定义中间件
    'app01.utils.mymiddleware.MD1',
    'app01.utils.mymiddleware.MD2',
]
# 输出
MD1请求来了
/xx/
MD2请求来了
MD2响应来了
MD1响应来了
[20/Nov/2020 09:33:28] "GET /xx/ HTTP/1.1" 200 2
MD1请求来了
/login/
MD1响应来了
[20/Nov/2020 09:33:37] "GET /login/ HTTP/1.1" 200 33

中间件认证白名单

不需要再再views.py中写装饰器

# mymiddleware.py
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import HttpResponse, redirect
from django.urls import reverse
# 中间件认证
class SessionAuth(MiddlewareMixin):

    def process_request(self, request):
        # 白名单
        print(request.path)
        white_list = [reverse('login'), ]  # 想让哪个路径过就再列表中加入,一般白名单列表放在settings文件中,然后再这里导入后引用,修改时再settings里改就行了
        print(white_list)
        if request.path in white_list:
            return None

        is_login = request.session.get('is_login')  # session认证
        if is_login:
            return None
        else:
            return redirect('login')

# settins
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',
    # 自定义中间件
    # 'app01.utils.mymiddleware.MD1',
    # 'app01.utils.mymiddleware.MD2',
    'app01.utils.mymiddleware.SessionAuth',
]

# views.py
def login(request):

    if request.method == 'GET':
        return render(request, 'login.html')
    else:
        name = request.POST.get('name')
        pwd = request.POST.get('pwd')
        print(name, pwd)
        if name == 'laowang' and pwd == '123':
            # ret = redirect('/home/')
            # ret.set_cookie('is_login', 0)
            # return ret
            request.session['is_login'] = True
            request.session['username'] = 'bo'
            # 1.生成了session_id
            # 2.在cookie里边加上了一个键值对
            # 3.存进django.session表中
            return redirect('/home/')
        else:
            return redirect('login')

def logout(request):
    request.session.flush()  # 清楚所有的cookie和session
    return redirect("/login/")

def home(request):
    return render(request, 'home.html')

def index(request):
    return render(request, 'index.html')

发表评论 取消回复

电子邮件地址不会被公开。

请输入正确格式的qq邮箱
请输入以http或https开头的URL,格式如:https://libo_sober.top