#!SESSION_SAVE_EVERY_REQUEST = True 设置根据最后一次操作设置登录超时时间
#!SESSION_EXPIRE_AT_BROWSER_CLOSE = True 设置是否关闭浏览器session 过期
#上面的在setting 里设置
from django.shortcuts import render,redirect,HttpResponse
#登录页面
def login(request):
if request.method == 'GET':
return render(request,'logins.html')
elif request.method == "POST":
user = request.POST.get('user')
pwd = request.POST.get('pwd')
if user == 'root' and pwd == "123":
#生成随机字符串
#写到用户浏览器cookie
#保存到session
#在随机字符串对应 相对应的字典
request.session['username'] = user
request.session['is_login'] = True
if request.POST.get('rmb',None) == '1':
#设置登录超市时间
request.session.set_expiry(10)
return redirect("/app01/index/")
else:
return render(request,'logins.html')
#登录成功后返回
def index(request):
#如果登录后返回页面 否则返回'请登录后访问'
if request.session.get("is_login",None):
return render(request,'login.html',{'username' :request.session['username']})
else:
return HttpResponse('请登录后访问')
#登录注销
def logout(request):
#清除当前session
request.session.clear()
return redirect("/app01/session/")
------------------------------------------------------------------------------------------------------------------------------------------------------
登录模板:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<form action="/app01/session/" method="post">
{% csrf_token %}
<input type="text" name="user" />
<input type="text" name="pwd" />
<input type="checkbox" name="rmb" value="1"> 10秒免登录
<input type="submit" value="提交">
</form>
</body>
</html>
返回模板:
<h1>欢迎登录:{{ username }},{{ request.session.username }}</h1>
<div style="height: 30px;width: 200px;background: #2ec0f6;text-align: center;line-height: 30px"><a href="/app01/logout/" style="font-size: 20px">注 销 </a></div>