一、簡單分頁javascript
涉及xss攻擊,須要用到mark_safe方法,使用此方法字符串傳輸到後端後,已html形式顯示,而非字符串html
HTML文件: 前端
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .pagination .page{ display: inline-block; padding: 5px; background-color: cyan; margin: 5px; } .pagination .page.active{ background-color: brown; color: white; } </style> </head> <body> <ul> {% for item in li %} <li>{{ item }}</li> {% endfor %} </ul> <div class="pagination"> {{ page_str }} </div> </body> </html>
處理文件:java
LIST = [] for i in range(109): LIST.append(i) from django.utils.safestring import mark_safe def user_list(request): current_page = request.GET.get('p',1) current_page = int(current_page) start = (current_page-1)*10 end = current_page*10 data = LIST[start:end] all_count = len(LIST) count,y = divmod(all_count,10) #整除、餘數 if y : #餘數不爲零 count +=1 page_list = [] for i in range(1,count+1): if i == current_page: temp = '<a class="page active" href="/user_list/?p=%s">%s</a>'%(i,i) else: temp = '<a class="page" href="/user_list/?p=%s">%s</a>'%(i,i) page_list.append(temp) page_str = mark_safe(''.join(page_list)) #xss攻擊 不加入此項 page_str傳到前端後,顯示的是字符串 #而不是html語言 # 另外一種方式在前端作 # {{ page_str|safe }} return render(request,'user_list.html',{'li':data,'page_str':page_str})
二、增長功能python
分頁數進行定製,添加上一頁、下一頁,增長跳轉功能,實現分頁的完整功能 jquery
HTML文件:redis
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .pagination .page{ display: inline-block; padding: 5px; background-color: cyan; margin: 5px; } .pagination .page.active{ background-color: brown; color: white; } </style> </head> <body> <ul> {% for item in li %} <li>{{ item }}</li> {% endfor %} </ul> <div class="pagination"> {{ page_str }} </div> </body> </html>
處理文件:數據庫
LIST = [] for i in range(199): LIST.append(i) from django.utils.safestring import mark_safe def user_list(request): current_page = request.GET.get('p',1) current_page = int(current_page) start = (current_page-1)*10 end = current_page*10 data = LIST[start:end] all_count = len(LIST) total_count,y = divmod(all_count,10) if y : total_count +=1 pager_num = 11 #頁碼數 page_list = [] if total_count < pager_num : #總頁面小於頁碼數 start_index = 1 end_index = total_count + 1 else: if current_page <= pager_num/2: #開頭 start_index = 1 end_index = pager_num + 1 elif current_page + (pager_num-1)/2 >= total_count: #中間 start_index = total_count - (pager_num-1) end_index = total_count + 1 else: #結尾 start_index = current_page - (pager_num-1)/2 end_index = current_page + (pager_num-1)/2 + 1 # 上下頁碼 if current_page == 1: prev = '<a class="page" href="javascript:void(0)">上一頁</a>' # 什麼都不幹 else: prev = '<a class="page" href="/user_list/?p=%s">上一頁</a>'%(current_page-1) page_list.append(prev) for i in range(int(start_index),int(end_index)): if i == current_page: temp = '<a class="page active" href="/user_list/?p=%s">%s</a>'%(i,i) else: temp = '<a class="page" href="/user_list/?p=%s">%s</a>'%(i,i) page_list.append(temp) if current_page == total_count: nex = '<a class="page" href="javascript:void(0)">下一頁</a>' # 什麼都不幹 else: nex = '<a class="page" href="/user_list/?p=%s">下一頁</a>'%(current_page+1) page_list.append(nex) # 跳轉 能夠寫到前端 jump = ''' <input type="text" /><a onclick="jumpTo(this,'/user_list/?p=');">GO</a> <script> function jumpTo(ths,base) { var val = ths.previousSibling.value; location.href = base + val; } </script> ''' page_list.append(jump) page_str = mark_safe(''.join(page_list)) return render(request,'user_list.html',{'li':data,'page_str':page_str})
三、優化完善django
頁碼代碼跟業務代碼分開,建立class類調用,最好單首創建目錄分開後端
HTML文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> .pagination .page{ display: inline-block; padding: 5px; background-color: cyan; margin: 5px; } .pagination .page.active{ background-color: brown; color: white; } </style> </head> <body> <ul> {% for item in li %} <li>{{ item }}</li> {% endfor %} </ul> <div class="pagination"> {{ page_str }} </div> </body> </html>
處理文件:
LIST = [] for i in range(199): LIST.append(i) class Page: def __init__(self, current_page, data_count, per_page_count=10, pager_num=7): self.current_page = current_page self.data_count = data_count self.per_page_count = per_page_count self.pager_num = pager_num @property def start(self): return (self.current_page - 1) * self.per_page_count @property def end(self): return self.current_page * self.per_page_count @property def total_count(self): v, y = divmod(self.data_count, self.per_page_count) if y: v += 1 return v def page_str(self, base_url): page_list = [] if self.total_count < self.pager_num: start_index = 1 end_index = self.total_count + 1 else: if self.current_page <= (self.pager_num + 1) / 2: start_index = 1 end_index = self.pager_num + 1 else: start_index = self.current_page - (self.pager_num - 1) / 2 end_index = self.current_page + (self.pager_num + 1) / 2 if (self.current_page + (self.pager_num - 1) / 2) > self.total_count: end_index = self.total_count + 1 start_index = self.total_count - self.pager_num + 1 if self.current_page == 1: prev = '<a class="page" href="javascript:void(0);">上一頁</a>' else: prev = '<a class="page" href="%s?p=%s">上一頁</a>' % (base_url, self.current_page - 1,) page_list.append(prev) for i in range(int(start_index), int(end_index)): if i == self.current_page: temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url, i, i) else: temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url, i, i) page_list.append(temp) if self.current_page == self.total_count: nex = '<a class="page" href="javascript:void(0);">下一頁</a>' else: nex = '<a class="page" href="%s?p=%s">下一頁</a>' % (base_url, self.current_page + 1,) page_list.append(nex) jump = """ <input type='text' /><a onclick='jumpTo(this, "%s?p=");'>GO</a> <script> function jumpTo(ths,base){ var val = ths.previousSibling.value; location.href = base + val; } </script> """ % (base_url,) page_list.append(jump) page_str = mark_safe("".join(page_list)) return page_str from django.utils.safestring import mark_safe def user_list(request): current_page = request.GET.get('p', 1) current_page = int(current_page) page_obj = Page(current_page,len(LIST)) data = LIST[page_obj.start:page_obj.end] page_str = page_obj.page_str("/user_list/") return render(request, 'user_list.html', {'li': data,'page_str': page_str})
一、概述
Cookie,有時也用其複數形式 Cookies,指某些網站爲了辨別用戶身份、進行 session 跟蹤而儲存在用戶本地終端上的數據(一般通過加密)。(能夠叫作瀏覽器緩存)
① 獲取Cookie
request.COOKIES['key'] request.COOKIES.get('key') request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None) 參數: default: 默認值 salt: 加密鹽 max_age: 後臺控制過時時間
② 設置Cookie
rep = HttpResponse(...) 或 rep = render(request, ...) #return的對象 rep.set_cookie(key,value,...) rep.set_signed_cookie(key,value,salt='加密鹽',...) 參數: key, 鍵 value='', 值 max_age=None, 超時時間 單位秒 expires=None, 超時時間(IE requires expires, so set it if hasn't been already.) 單位日期 path='/', Cookie生效的路徑,/ 表示根路徑,特殊的:跟路徑的cookie能夠被任何url的頁面訪問 指定生效路徑 domain=None, Cookie生效的域名 secure=False, https傳輸改成True httponly=False 只能http協議傳輸,沒法被JavaScript獲取(不是絕對,底層抓包能夠獲取到也能夠被覆蓋) 補充: # max_age 10秒失效 result.set_cookie('username',u,max_age=10) # expires 設置失效日期 import datetime current_date = datetime.datetime.utcnow() current_date = current_date + datetime.timedelta(seconds=5) result.set_cookie('username',u,expires=current_date) # 加密 obj = HttpResponse('s') obj.set_signed_cookie('username',"kangbazi",salt="asdfasdf") request.get_signed_cookie('username',salt="asdfasdf")
因爲cookie保存在客戶端的電腦上,因此,JavaScript和jquery也能夠操做cookie
<script src='/static/js/jquery.cookie.js'></script> $.cookie("list_pager_num", 30,{ path: '/' }); #key vaule 字典
二、用戶登陸
利用cookie作用戶登陸頁面,只有登陸成功才能進入到後臺管理
HTML文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <h1>歡迎登陸:{{ current_user }}</h1> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <form action="/login/" method="POST"> <input type="text" name="username" placeholder="用戶名" /> <input type="password" name="pwd" placeholder="密碼" /> <input type="submit" /> </form> </body> </html>
處理文件:
user_info = { 'James':{'pwd':'123456'}, 'lianzhilei':{'pwd':'123456'} } def login(request): if request.method == 'GET': return render(request,'login.html') if request.method == 'POST': u = request.POST.get('username') p = request.POST.get('pwd') dic = user_info.get(u) if not dic: return render(request,'login.html') if dic['pwd']== p: result = redirect('/index/') result.set_cookie('username',u) #設置cookie值 return result else: return render(request, 'login.html') def index(request): v = request.COOKIES.get('username') #獲取cookie值 if not v : return redirect('/login/') return render(request,'index.html',{'current_user':v})
三、定製分頁
根據用戶選擇的數字,顯示頁面的數量
HTML文件:
<body> <ul> {% for item in li %} <li>{{ item }}</li> {% endfor %} </ul> <div> <select id='pg' onchange="ChangePageSize(this)"> <option value="10">10</option> <option value="30">30</option> <option value="50">100</option> </select> </div> <div class="pagination"> {{ page_str }} </div> <script src="/static/jquery-1.12.4.js"></script> <script src="/static/jquery.cookie.js"></script> <script> $(function () { var v = $.cookie('per_page_count',{'path':'/user_list/'}); $('#pg').val(v); }); function ChangePageSize(ths) { var v = $(ths).val(); $.cookie('per_page_count',v,{'path':'/user_list/'}); location.reload() } </script> </body>
處理文件:
from django.utils.safestring import mark_safe def user_list(request): current_page = request.GET.get('p', 1) current_page = int(current_page) per_page_count = request.COOKIES.get('per_page_count',10) #獲取cookie值 per_page_count = int(per_page_count) page_obj = Page(current_page,len(LIST),per_page_count) data = LIST[page_obj.start:page_obj.end] page_str = page_obj.page_str("/user_list/") return render(request, 'user_list.html', {'li': data,'page_str': page_str})
四、登陸認證(裝飾器)
FBV:
1 from django.shortcuts import render 2 3 from django.shortcuts import HttpResponse,redirect 4 from django.shortcuts import reverse 5 6 user_info = { 7 'James': {'pwd': '123456'}, 8 'lianzhilei': {'pwd': '123456'} 9 } 10 11 def login(request): 12 if request.method == 'GET': 13 return render(request, 'login.html') 14 if request.method == 'POST': 15 u = request.POST.get('username') 16 p = request.POST.get('pwd') 17 dic = user_info.get(u) 18 if not dic: 19 return render(request, 'login.html') 20 if dic['pwd'] == p: 21 result = redirect('/index/') 22 result.set_cookie('username', u) # 設置cookie值 23 return result 24 else: 25 return render(request, 'login.html') 26 27 def auth(func): 28 def inner(request,*args,**kwargs): 29 v = request.COOKIES.get('username') # 獲取cookie值 30 if not v: 31 return redirect('/login/') 32 return func(request,*args,**kwargs) 33 return inner 34 35 @auth #認證裝飾 36 def index(request): 37 v = request.COOKIES.get('username') 38 return render(request, 'index.html', {'current_user': v})
CBV:
1 from django.shortcuts import render 2 3 from django.shortcuts import HttpResponse,redirect 4 from django.shortcuts import reverse 5 6 user_info = { 7 'James': {'pwd': '123456'}, 8 'lianzhilei': {'pwd': '123456'} 9 } 10 11 def login(request): 12 if request.method == 'GET': 13 return render(request, 'login.html') 14 if request.method == 'POST': 15 u = request.POST.get('username') 16 p = request.POST.get('pwd') 17 dic = user_info.get(u) 18 if not dic: 19 return render(request, 'login.html') 20 if dic['pwd'] == p: 21 result = redirect('/index/') 22 result.set_cookie('username', u) # 設置cookie值 23 return result 24 else: 25 return render(request, 'login.html') 26 27 def auth(func): 28 def inner(request,*args,**kwargs): 29 v = request.COOKIES.get('username') # 獲取cookie值 30 if not v: 31 return redirect('/login/') 32 return func(request,*args,**kwargs) 33 return inner 34 35 from django import views 36 from django.utils.decorators import method_decorator 37 38 @method_decorator(auth,name='dispatch') #第一種方式 39 class Order(views.View): 40 41 # @method_decorator(auth) #第二種方式 42 # def dispatch(self, request, *args, **kwargs): 43 # return super(Order,self).dispatch(request, *args, **kwargs) 44 45 # @method_decorator(auth) #單獨添加 46 def get(self,reqeust): 47 v = reqeust.COOKIES.get('username111') 48 return render(reqeust,'index.html',{'current_user': v}) 49 50 def post(self,reqeust): 51 v = reqeust.COOKIES.get('username111') 52 return render(reqeust,'index.html',{'current_user': v}) 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 LIST = [] 70 for i in range(199): 71 LIST.append(i) 72 73 class Page: 74 def __init__(self, current_page, data_count, per_page_count=10, pager_num=7): 75 self.current_page = current_page 76 self.data_count = data_count 77 self.per_page_count = per_page_count 78 self.pager_num = pager_num 79 80 @property 81 def start(self): 82 return (self.current_page - 1) * self.per_page_count 83 84 @property 85 def end(self): 86 return self.current_page * self.per_page_count 87 88 @property 89 def total_count(self): 90 v, y = divmod(self.data_count, self.per_page_count) 91 if y: 92 v += 1 93 return v 94 95 def page_str(self, base_url): 96 page_list = [] 97 98 if self.total_count < self.pager_num: 99 start_index = 1 100 end_index = self.total_count + 1 101 else: 102 if self.current_page <= (self.pager_num + 1) / 2: 103 start_index = 1 104 end_index = self.pager_num + 1 105 else: 106 start_index = self.current_page - (self.pager_num - 1) / 2 107 end_index = self.current_page + (self.pager_num + 1) / 2 108 if (self.current_page + (self.pager_num - 1) / 2) > self.total_count: 109 end_index = self.total_count + 1 110 start_index = self.total_count - self.pager_num + 1 111 112 if self.current_page == 1: 113 prev = '<a class="page" href="javascript:void(0);">上一頁</a>' 114 else: 115 prev = '<a class="page" href="%s?p=%s">上一頁</a>' % (base_url, self.current_page - 1,) 116 page_list.append(prev) 117 118 for i in range(int(start_index), int(end_index)): 119 if i == self.current_page: 120 temp = '<a class="page active" href="%s?p=%s">%s</a>' % (base_url, i, i) 121 else: 122 temp = '<a class="page" href="%s?p=%s">%s</a>' % (base_url, i, i) 123 page_list.append(temp) 124 125 if self.current_page == self.total_count: 126 nex = '<a class="page" href="javascript:void(0);">下一頁</a>' 127 else: 128 nex = '<a class="page" href="%s?p=%s">下一頁</a>' % (base_url, self.current_page + 1,) 129 page_list.append(nex) 130 131 jump = """ 132 <input type='text' /><a onclick='jumpTo(this, "%s?p=");'>GO</a> 133 <script> 134 function jumpTo(ths,base){ 135 var val = ths.previousSibling.value; 136 location.href = base + val; 137 } 138 </script> 139 """ % (base_url,) 140 141 page_list.append(jump) 142 143 page_str = mark_safe("".join(page_list)) 144 145 return page_str 146 147 from django.utils.safestring import mark_safe 148 def user_list(request): 149 current_page = request.GET.get('p', 1) 150 current_page = int(current_page) 151 152 per_page_count = request.COOKIES.get('per_page_count',10) #獲取cookie值 153 per_page_count = int(per_page_count) 154 155 page_obj = Page(current_page,len(LIST),per_page_count) 156 157 data = LIST[page_obj.start:page_obj.end] 158 159 page_str = page_obj.page_str("/user_list/") 160 161 return render(request, 'user_list.html', {'li': data,'page_str': page_str}) 162 163 164 165 166 167 # def user_list(request): 168 # current_page = request.GET.get('p',1) 169 # current_page = int(current_page) 170 # 171 # start = (current_page-1)*10 172 # end = current_page*10 173 # data = LIST[start:end] 174 # 175 # all_count = len(LIST) 176 # count,y = divmod(all_count,10) #整除、餘數 177 # if y : #餘數不爲零 178 # count +=1 179 # 180 # page_list = [] 181 # for i in range(1,count+1): 182 # if i == current_page: 183 # temp = '<a class="page active" href="/user_list/?p=%s">%s</a>'%(i,i) 184 # else: 185 # temp = '<a class="page" href="/user_list/?p=%s">%s</a>'%(i,i) 186 # 187 # page_list.append(temp) 188 # 189 # page_str = mark_safe(''.join(page_list)) #xss攻擊 不加入此項 page_str傳到前端後,顯示的是字符串 190 # #而不是html語言 191 # # 另外一種方式在前端作 192 # # {{ page_str|safe }} 193 # 194 # return render(request,'user_list.html',{'li':data,'page_str':page_str})
一、概述
二者區別:Cookie是保存在用戶瀏覽器端的鍵值對,Session是保存在服務器端的鍵值對;Cookie作用戶驗證的時,敏感信息不適合放在Cookie中,別人能夠分析存放在本地的Cookie並進行Cookie欺騙,考慮到安全應當使用Session;用戶驗證時二者要結合使用,Session可保存到文件,內存,數據庫任意地方
① 獲取
# 獲取Session中數據 request.session['k1'] request.session.get('k1', None)
② 生成
# 生成Session中數據 request.session['k1'] = 123 request.session.setdefault('k1', 123) # 存在則不設置
③ 刪除
# 刪除Session中某條數據 del request.session['k1'] # 刪除當前用戶的全部Session數據 request.session.delete("session_key") request.session.clear() #註銷時可用
④ 鍵值對
# 全部 鍵、值、鍵值對 request.session.keys() request.session.values() request.session.items() request.session.iterkeys() request.session.itervalues() request.session.iteritems()
⑤ 超時時間
# 設置超時時間 request.session.set_expiry(value) #默認超時時間爲兩週 *若是value是個整數,session會在些秒數後失效。 *若是value是個datatime或timedelta,session就會在這個時間後失效。 *若是value是0, 用戶關閉瀏覽器session就會失效。 *若是value是None, session會依賴全局session失效策略。
⑥ 其餘
# 用戶session的隨機字符串 request.session.session_key # 將全部Session失效日期小於當前日期的數據刪除 request.session.clear_expired() # 檢查 用戶session的隨機字符串 在數據庫中是否 通常用不到 request.session.exists("session_key")
二、用戶登陸
利用Session作用戶登陸頁面,只有登陸成功才能進入到後臺管理
HTML文件:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="/login/" method="post"> <input type="text" name="user" /> <input type="text" name="pwd" /> <input type="checkbox" name="session" value="1"/> 保存1個月 <input type="submit" value="提交" /> </form> </body> </html>
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> {{ request.session.username }} </body> </html>
處理文件:
def login(request): 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": # 生成隨機字符串 # 寫到用戶瀏覽器Cookie # 保存到Session中 # 在隨機字符串對應的字典中設置相關內容... request.session['username'] = user request.session['if_login'] = True #可不加 直接判斷username也能夠 if request.POST.get('session') == '1': #單獨設置超時時間,當前session生效,不影響全局 request.session.set_expiry(10) #10秒 return redirect('/index/') else: return redirect('/login/') def index(request): # 獲取當前用戶的隨機字符串 # 根據隨機字符串獲取對應信息 if request.session.get('if_login'): return render(request, 'index.html') else: return redirect('/login/')
三、數據庫存儲Session
Django默認支持Session,而且默認是將Session數據存儲在數據庫中,即:django_session表中 配置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,默認修改以後才保存(默認) # 設置Ture後,每次點擊頁面,時間更新
四、緩存存儲Session
配置settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # 引擎 SESSION_CACHE_ALIAS = 'default' # 使用的緩存別名(默認內存緩存,也能夠是memcache),此處別名依賴緩存的設置 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,默認修改以後才保存
能夠設置爲Memcache緩存,默認不支持redis(可使用網上插件)
配置settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.cache' # 引擎 SESSION_CACHE_ALIAS = 'db' # 使用的緩存別名,此處別名依賴緩存的設置 CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': [ '172.19.26.240:11211', '172.19.26.242:11211', ] }, 'db': { 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache', 'LOCATION': [ '172.19.26.240:11211', '172.19.26.242:11211', ] } }
五、文件存儲Session
配置 settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.file' # 引擎 SESSION_FILE_PATH = None # 緩存文件路徑,若是爲None,則使用tempfile模塊獲取一個臨時地址tempfile.gettempdir() # 如:/var/folders/d3/j9tj0gz93dg06bmwxmhh6_xm0000gn/T 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,默認修改以後才保存
六、緩存+數據庫Session
數據庫用於作持久化,緩存用於提升效率,先去緩存中取數據,緩存沒有再去數據庫中取,而後在緩存中存一份 配置settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db' # 引擎
七、加密cookie Session
數據都存在於客戶端 配置settings.py SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' # 引擎
注:當使用Session時,須要執行makemigrations和 migrate,數據庫上會自動生成django_session數據表
《第二十一章》