django的session的登录验证

 

urls.py

from django.conf.urls import url
from django.contrib import admin
from app01 import views
urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^login/', views.login, name='login'),
    url(r'^index/', views.index, name='index'),
    url(r'^logout/', views.logout, name='logout'),
]

views.py

# -*- coding:utf-8 -*-
from django.shortcuts import render, redirect

# Create your views here.

user_info = {
    'lily': {'pwd': '123'},
    'rose': {'pwd': '123'}
}

def login(request):
    if request.method == 'POST':
        u = request.POST.get('uu')
        p = request.POST.get('pp')
        s = request.POST.get('ss')
        if user_info.get(u):
            if p == user_info.get(u).get('pwd'):
                # 生成随机字符串保存在cookie中 sessionid : xxxxx
                # 保存在session中(数据库)
                # 在服务端,每个随机字符串对应一个字典,保存信息
                request.session['user111'] = u
                request.session['is_login'] = True
                # 设置自动注销登录
                if s == '1':
                # 括号中数字单位为秒
                    request.session.set_expiry(5)
                elif s == '2':
                    request.session.set_expiry(20)
                elif s == '3':
                    request.session.set_expiry(60)

                return redirect('/index/')
    return render(request, 'login.html')

def index(request):
    u = request.session.get('user111')
    if request.session.get('is_login', None):
        return render(request, 'index.html', {'u': u})
    else:
        return render(request, 'login.html')

def logout(request):
    request.session.clear()
    return redirect('/login/')

template-login




    
    


    
{% csrf_token %}

自动退出登录时间:

template-index




    
    


    welcome to {{ u }}
exit


你可能感兴趣的:(django的session的登录验证)