自定义用户登录,会话保持,自动跳转

自定义用户登录,使用自定义的表存放用户信息,使用session保持会话连接,在关闭浏览器后session过期,登录后可以自动跳转会原来的页面:

session管理:http://www.cnblogs.com/dreamer-fish/p/5434962.html

# -*- coding: UTF-8 -*-
from django.shortcuts import render
from django.http import HttpResponse,HttpResponseRedirectfrom aptest.forms import hvform,testform,vmform,lusersform
from aptest.models import lusers
from django.contrib.sessions.models import Session# Create your views here.

global user_loggedin,login_url,dict_sessions
user_loggedin='Guest' #设置未登录的默认用户名为Guest
login_url = '/login' #设置登录页面url
dict_sessions={} #设置session dict用于存放登录后的用户sessionkey,用于判断该用户是否已登录。用户注销后则删掉相应用户的dict dey

#定义登录前检查函数
def login_req(url=login_url):
    def getFun(func):
        def wrapper(request,*args, **kv):
            global user_loggedin #将user_loggedin设置为global,否则其他view获取不到该值
            request.session['backurl']  = request.path #获取当前页面的url,登录成功后自动跳转回该页面,获取不到则为None
            #request.session.set_expiry(1800)
            userinfo = request.session.get('s_username',None) #获取session,如果获取不到则设置为None       
            if not userinfo:
                #在此取出login页面的绝对路径,可适应任意一级页面跳转到login页面
                return HttpResponseRedirect('/' + request.path.strip().split('/')[1] + login_url) #没有登录,则跳转到登录页面    
            else:
                user_loggedin=request.session['s_username']  #获取当前登录用户名 
                #print 'deco dict_sessions-first::::::',dict_sessions #,dict_sessions[str(request.session['s_username'])]
                try:
                    #用户第一次登录后将相应的username和sessionkey放入到字典中,当用户第二次登录后,使用新的sessionkey同之前存在字典中的sessionkey进行比较,
                    #如果不同,则从数据库中删掉第一次的session,使之失效,同时使用新的sessionkey更新字典;如果相同,则字典中的sessionkey保持不变,视之为同一次登录
                    if request.session.session_key <> dict_sessions[request.session['s_username']]:
                        Session.objects.get(pk=dict_sessions[request.session['s_username']]).delete()
                        dict_sessions[request.session['s_username']] = request.session.session_key
                except KeyError:
                    #如果用户是第一次登录,则取不到字典的key值,于是就将当前的username和sessionkey放入到字典中
                    dict_sessions[request.session['s_username']] = request.session.session_key

            return func(request,*args, **kv)   
        return wrapper
    return getFun


@login_req()
def index(request): #主页
    return HttpResponse(u"Welcome to my index page.")


@login_req()
def add(request):
    a=3
    b=55
    c=int(a)+int(b)
    err=[]
    if request.method == 'POST':
        #print request.POST['hvname'],request.POST['hvip']
        print request.method
        form = hvform(request.POST)
        
        if form.is_valid(): #判断输入数据是否合法
            #print form
            #print form.cleaned_data['name'],form.cleaned_data['ip']
            fc = form.cleaned_data
            print fc['name'],fc['ip']
        else:
            err.append(form.errors) #输出错误信息
    else:
        form = hvform()

    hour_offset= time.ctime()
    ls = range(10)
    context={'hour_offset':hour_offset,'ls':ls,'err':err,'user_loggedin':user_loggedin}
    return render(request,'aptest/form.html',context)


@login_req()
def testvw(request):
    err=[]
    if request.method == 'POST':
        print request.method
        form = vmform(request.POST)
        if form.is_valid(): #判断输入数据是否合法
            fc = form.cleaned_data
            print fc['hvname'],fc['name'],fc['cpu']
        else:
            err.append(form.errors) #输出错误信息
    else:
        form = vmform()
    context={'err':err,'user_loggedin':user_loggedin}
    return render(request,'aptest/current_datetime.html',context)


#定义用户登录函数,并判断登录后是否自动跳转到前一个页面,还是跳转到主页
def login(request):
    user_loggedin='Guest'
    errors_list=[]
    if request.method == 'POST':
        form = lusersform(request.POST)
        if form.is_valid(): 
            fc = form.cleaned_data
            #print fc['name'],fc['password']
            try:
                usero = lusers.objects.get(name=fc['name'])
                if usero.password == fc['password']:
                    request.session['s_username'] = usero.name  #设置该用户的session
                    user_loggedin = usero.name #获取登陆后用户的用户名
                    #print 'login -get backurl: ',request.session.get('backurl'),request.session['s_username']
                    if request.session.get('backurl') is not None: #检查跳转前的url是否存在
                        redirecturl = request.session['backurl']    
                    else:
                        redirecturl = '/' + request.path.strip().split('/')[1] #跳转前的url不存在则跳转到主页
                    return HttpResponseRedirect(redirecturl)
                else:
                    errors_list.append('password is not correct!')

            except Exception:
                errors_list.append(fc['name'] + ' Doesnot Exists')

        else:
            errors_list.append(form.errors) #输出字段格式错误信息
    else:
        form = lusersform()
        if request.session.get('s_username') is not None:
            user_loggedin = request.session.get('s_username')

    context={'errors_list':errors_list,'user_loggedin':user_loggedin}
    return render(request,'aptest/login.html',context)

#定义用户注销函数
def logout(request):
    #user_loggedin='Guest'
    try:
        #删除保存用户名和跳转前url的session
        dict_sessions.pop(request.session['s_username'])
        for key in list(request.session.keys()):
            del request.session[key]
    except KeyError:
        pass
    #注销登陆后跳转到原页面
    #return HttpResponseRedirect(request.META.get('HTTP_REFERER', '/'))
    return HttpResponseRedirect('../login')

 

修改关闭浏览器后session过期:

1.在settings.py最后一行添加 SESSION_EXPIRE_AT_BROWSER_CLOSE=True 
2.清空已保存的session:delete from django_session
3.清空IE缓存
4.重新测试OK,使用print request.session.get_expire_at_browser_close()查看session是否在浏览器关闭后失效

 

你可能感兴趣的:(自定义用户登录,会话保持,自动跳转)