django session操作 middlewaremixin拦截器

//app3\middleware.py
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
from django.shortcuts import redirect,render

NO_LOGIN_URLS=["/login"]

class MyMiddleware(MiddlewareMixin):
    def process_request(self,request):
        # print('process_request',request.path)
        # print(request.session.__dict__)
        # print(request.session.keys())
        # print(request.session.items())

        #  如果session里有user字段,就不拦截(return),否则return redirect
        if 'user' in request.session:

        #  如果session里有user字段,且值不为空
        # if request.session.get('user'):
            return
        elif request.path not in NO_LOGIN_URLS:  # 请求的不是登录界面
            request.session['redirect_url']=request.path
            # 以下三种方法都可以拦截原来的请求
            return redirect("/login")
            # return render(request,"login.html")
            # return HttpResponse("请先登录")
 
    def process_response(self,request,response):
        # print("process_response")
        return response   # 必须返回相应对象
//app1\views.py
from datetime import datetime
from app2 import models
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.conf import settings
from baseApp import utils

def login(request):
    # print(request.method,request.path)
    if request.method == "GET":
        # print(request.GET)
        return render(request, "login.html", {'redirect_url': request.path})
    if request.method == "POST":
        # print(request.POST)
        if request.POST.get('user'):
            # pwd = request.POST['password']
            # print(type(pwd), pwd)
            request.session['user'] = request.POST.get('user')

            # set_expiry(value),设置过期时间。value的值有几种情况:
            # 整数: 单位为秒,表示在value秒之后session失效
            # datetime对象: 会在datetime指定时间之后失效
            # 0: 关闭浏览器之后就失效
            # None: 依赖全局的session失效策略配置
            request.session.set_expiry(11)

            redirect_url=request.session.get('redirect_url') 
            redirect_url =redirect_url if redirect_url else '/a1/t1'
            # print(request.session.items(),1,request.session.get_expiry_date())

            # 清除某个session
            request.session.pop('redirect_url')
            # print(request.session.items(),2)
            return redirect(redirect_url)
    return render(request, "login.html", {'msg': 'password error'})

def logout(request):
    print(request.session.__dict__,1)
    request.session.clear()
    print(request.session.__dict__,2)
    return redirect('/login')

//app1\templates\login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <form method="post" action="login">
        {% csrf_token %}
        <input  name="user" value="账号1" />
        <input  name="password" value="密码1" />
        <input type="hidden" name="redirect_url" />
        <div style="color:red">{{msg}}</div>
        <button type="submit" >提交</button>
    </form>
</body>
</html>
//djdemo1\urls.py
from django.urls import path
import app1.views as a1v

urlpatterns = [
	path('login', a1v.login),
	path('logout', a1v.logout),]
//djdemo1\settings.py
*************省略**********
MIDDLEWARE = [
*************省略**********
    'app3.middleware.MyMiddleware',
]
*************省略**********

登录后,在template里{{request.session.user}}可以查看request.session.get(‘user’)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值