Django 中 Cookie 使用即三天免登陆

需求

访问 http://127.0.0.1:8000/student/login/
点击记住密码,设置缓存保存三天,三天免登陆
不点击记住密码,再次登录时需要手动输入密码

#新创建项目 test31
#新创建 app student
python manage.py startapp student
#配置 settings.py
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'student'
]
# 配置urls test31/urls.py

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^student/',include('student.urls'))
]
#配置子路由
#coding=utf-8

from django.conf.urls import url
import views
urlpatterns = [
    url(r'^login/$',views.login_view)
]
#配置视图 views.py
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.http import HttpResponse
from django.shortcuts import render, redirect


# Create your views here.
def login_view(request):
    if request.method == 'GET':
        #判断登录时是否有cookies
        if request.COOKIES.has_key('loginUser'):
            #获取用户名和密码
            loginUser = request.COOKIES.get('loginUser','').split(',')
            uname = loginUser[0]
            pwd = loginUser[1]
            #传递给前端页面渲染
            return render(request,'login.html',{'uname':uname,'pwd':pwd})
        else:
            return render(request,'login.html')
    else:
        #获取请求参数
        uname = request.POST.get('uname','')
        pwd = request.POST.get('pwd','')

        response = HttpResponse()
        if uname == 'zhangsan' and pwd == '123':
            #赋值响应内容
            response.content = 'login success!'

            # 是否记住密码;判断前端页面传过来的 flag 是否为1 ,为1 那么再次登录界面的时候成为 get 请求,将cookie 信息填入空白处
            if request.POST.get('flag') == '1':
                response.set_cookie('loginUser',uname+','+pwd,max_age=3*24*60*60,path='/student/')
                return response
            else:
                #清空cookie 信息中的 loginUser
                response.delete_cookie('loginUser',path='/student/')
                return response
        else:
            # 重定向至重新登录页面
            return redirect('/student/login')

#配置 templates/login.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

    <form action="/student/login/" method="post">
        {% csrf_token %}
        <p>
            <label for="sn">姓名:</label><input type="text" name="uname" id="sn" value="{{ uname }}"/>
        </p>
        <p>
            <label for="pd">密码:</label><input type="password" name="pwd" id="pd" value="{{ pwd }}"/>
        </p>
        <p>
            <input type="checkbox" name="flag" value="1" checked/>记住密码
        </p>
        <p>
            <input type="submit" value="login"/>
        </p>

    </form>

</body>
</html>


再次访问http://127.0.0.1:8000/student/login/ 时候不会自动填充账号和密码,也没有cookie

效果: 点击登录时记住密码


再次访问http://127.0.0.1:8000/student/login/ 时候会自动填充账号和密码,并有cookie

补充python3 代码

from django.shortcuts import render
from django.http import HttpResponse
# Create your views here.
def login(request):
    if request.method=='POST':
        uname=request.POST.get('uname')
        passwd=request.POST.get('passwd')
        if uname=='lisi' and passwd=='123':
            #HttpResponse 源代码是一个类class,创建一个类对象
            response=HttpResponse()
            #创建一个类实例属性
            response.content='登录成功---'
            print ('---------------------------')
            print (request.POST.get('remeber'))
            if request.POST.get('remeber') == '1':
                #设置cookie 内容为(键,值,有效期,生效的路径)
                response.set_cookie('loginUser',uname + ',' + passwd, max_age=3 * 24 * 60 * 60, path='/student/login')
                return response
            else:
                #清除cookie 信息中的loginUser
                response.delete_cookie('loginUser',path='/student/login')
                print ('xxxxxxxxxxxxxxxxxxxxxxxxx')
                return response
        else:
            response=HttpResponse()
            response.content='账号密码不对!'
            return  response
    else:
        if request.COOKIES.get('loginUser'):
            #获取用户名和密码
            loginUser = request.COOKIES.get('loginUser','').split(',')
            print (loginUser)
            uname = loginUser[0]
            pwd = loginUser[1]
            #传递给前端页面渲染
            return render(request,'login/login.html',{'uname':uname,'pwd':pwd})
        else:
            return render(request,'login/login.html')


posted @ 2020-12-10 15:26  lixinliang  阅读(380)  评论(0编辑  收藏  举报