1. Session
基于Cookie做用户验证时:敏感信息不适合放在cookie中


a. Session原理
Cookie是保存在用户浏览器端的键值对
Session是保存在服务器端的键值对

b. Cookie和Session对比

c. Session配置(缺少cache)

d. 示例:实现两周自动登陆
- request.session.set_expiry(60*10)
- SESSION_SAVE_EVERY_REQUEST = True

PS: cookie中不设置超时时间,则表示关闭浏览器自动清除


- session依赖于cookie
- 服务器session
request.session.get()
request.session[x] = x

request.session.clear()

- 配置文件中设置默认操作(通用配置):
SESSION_COOKIE_NAME = "sessionid" # Session的cookie保存在浏览器上时的key,即:sessionid=随机字符串(默认)
SESSION_COOKIE_PATH = "/" # Session的cookie保存的路径(默认)
SESSION_COOKIE_DOMAIN = None # Session的cookie保存的域名(默认)
SESSION_COOKIE_SECURE = False # 是否Https传输cookie(默认)
SESSION_COOKIE_HTTPONLY = True # 是否Session的cookie只支持http传输(默认)
SESSION_COOKIE_AGE = 1209600 # Session的cookie失效日期(2周)(默认)
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否关闭浏览器使得Session过期(默认)
# set_cookie('k',123)
SESSION_SAVE_EVERY_REQUEST = False # 是否每次请求都保存Session,默认修改之后才保存(默认)
from django.shortcuts import render,redirect,HttpResponse

def login(request):
# from django.conf import settings
# print(settings.CSRF_HEADER_NAME)
# HTTP_X_CSRFTOKEN
# X-CSRFtoken

if request.method == "GET":
return render(request,'login.html')
elif request.method == "POST":
user = request.POST.get('user')
pwd = request.POST.get('pwd')
if user == 'root' and pwd == "123":
# session中设置值
request.session['username'] = user
request.session['is_login'] = True
if request.POST.get('rmb',None) == '1':
# 超时时间
request.session.set_expiry(10)
return redirect('/index/')
else:
return render(request,'login.html')
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<form action="/login/" 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="提交" />
<input id="btn1" type="button" value="按钮" />
<input id="btn2" type="button" value="按钮" />
</form>

<script src="/static/jquery-1.12.4.js"></script>
<script src="/static/jquery.cookie.js"></script>
<script>
$(function(){
$.ajaxSetup({
beforeSend: function(xhr,settings){
xhr.setRequestHeader('X-CSRFtoken', $.cookie('csrftoken'));
}
});

$('#btn1').click(function () {
$.ajax({
url: '/login/',
type:"GET",
data: {'user': 'root', 'pwd': '123'},
// headers: {'X-CSRFtoken': $.cookie('csrftoken')},
success:function(arg){

}
})
});
})
</script>
</body>
</html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1>欢迎登录:{{ username }}, {{ request.session.username }}</h1>
<a href="/logout/">注销</a>
</body>
</html>

 

心有猛虎,细嗅蔷薇