django之session配置

session应用示例

 1 from django.shortcuts import render
 2 from django.shortcuts import HttpResponse
 3 from django.shortcuts import redirect
 4 
 5 # Create your views here.
 6 user = "a"
 7 pwd = "a"
 8 def login(request):
 9     if request.method == "GET":
10         return render(request,"login.html")
11     elif request.method == "POST":
12         u = request.POST.get("user")
13         p = request.POST.get("password")
14         if u == user and p ==pwd:
15             #session中设置值
16             request.session["username"] = u
17             request.session["is_login"] = True
18             if request.POST.get("rmb",None) == "1":
19                 #设置超时时间
20                 request.session.set_expiry(10)
21             return redirect("/index")
22         else:
23             return render(request,"login.html")
24 def index(request):
25     #session中获取值
26     if request.session.get("is_login",None):
27         current_user = request.session["username"]
28         return render(request,"index.html",{"current_user":current_user})
29     else:
30         return redirect("/login")
31 def logout(request):
32     #注销
33     request.session.clear()
34     return redirect("/login")

settings文件内配置

Django默认支持Session,并且默认是将Session数据存储在数据库中,即:django_session 表中。

 
a. 配置 settings.py
 
    SESSION_ENGINE = 'django.contrib.sessions.backends.db'   # 引擎(默认)
     
    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过期(默认)
    SESSION_SAVE_EVERY_REQUEST = False                       # 是否每次请求都保存Session,默认修改之后才保存(默认)
详细配置 请访问:   http://www.cnblogs.com/wupeiqi/articles/5246483.html
posted @ 2017-01-12 00:11  李瑞鑫  阅读(7996)  评论(0编辑  收藏  举报