自定义用户登录,会话保持,登录后自动跳转原页面
自定义用户登录,使用自定义的表存放用户信息,使用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是否在浏览器关闭后失效
settings中
SESSION_COOKIE_AGE=60*30 30分钟。
SESSION_EXPIRE_AT_BROWSER_CLOSE False:会话cookie可以在用户浏览器中保持有效期。True:关闭浏览器,则Cookie失效。
SESSION_COOKIE_DOMAIN 生效站点
SESSION_COOKIE_NAME cookie中保存session的名称
Session使用比较简单,在request.session是一个字典类。session是保存在数据库中的。
判断所请求的URL中是否包含有next参数,如果有则跳转到next页面(即登录前页面)
def login(request): nextfullurl = request.get_full_path() #获取完整的url,通过next判断是否需要跳转到原页面 if request.method == 'POST': u = request.POST.get('username').strip() p = request.POST.get('password') user = authenticate(username=u, password=p) if user is not None: auth_login(request, user) if request.GET.has_key('next'): #有时可能需要通过request.POST.has_key('next')判断,看前端以何种方式提交该URL,默认submit提交为GET方式 R_url = request.GET['next'] else: R_url = '/sinfors/srvinfors' try: mgmtusers.objects.get(sAMAccountName=u) return HttpResponseRedirect(R_url) except Exception: errors_list=[] errors_list.append(u + ' does not exist') return render(request,'sinfors/loginm.html',{'errors':errors_list[0]}) else: errors_list=[] try: if not auth_User.objects.get(username = u).check_password(p): errors_list.append(u + ' password is not correct') except auth_User.DoesNotExist: errors_list.append(u + ' does not exist1') return render(request,'sinfors/loginm.html',{'errors':errors_list[0]}) return render(request,'sinfors/loginm.html')
在settings.py中统一设置LOGIN_URL
LOGIN_URL = '/sinfors/login/' #Login Page. #LOGIN_REDIRECT_URL='/'
再使用login_required的时候可以直接使用,如下:
@login_required
def srvmgmt_domainnames(request):
通过使用url中的next关键字判断需要跳转到的页面:
def login(request): nextfullurl = request.get_full_path() #获取完整的url,通过next判断是否需要跳转到原页面 if request.method == 'POST': u = request.POST.get('username').strip() p = request.POST.get('password') user = authenticate(username=u, password=p) if user is not None: auth_login(request, user) try: mgmtusers.objects.get(sAMAccountName=u) if nextfullurl.find('?next=') <> -1: #如果包含有next,则设置需要跳转的url R_url = nextfullurl.split('?next=')[1] else: R_url = '/sinfors/srvinfors' return HttpResponseRedirect(R_url) except Exception: errors_list=[] errors_list.append(u + ' does not exist') return render(request,'sinfors/loginm.html',{'errors':errors_list[0]}) else: errors_list=[] try: if not auth_User.objects.get(username = u).check_password(p): errors_list.append(u + ' password is not correct') except auth_User.DoesNotExist: errors_list.append(u + ' does not exist1') return render(request,'sinfors/loginm.html',{'errors':errors_list[0]}) return render(request,'sinfors/loginm.html')