Django---Cookie && Session
什麽是COOKIE
保存在瀏覽器端的鍵值對
1、服務端可以在瀏覽器上設置COOKIE,保存在瀏覽器上
2、每次請求會攜帶COOKIE
3、Cookie 有時間限制
4、可用來做登錄與其他事情
使用場景:
1、登錄
2、多少天免登陸
3、記住用戶的某些瀏覽習慣
4、簡單請求限制
網站自動發送本網站 相關的所有COOKIE
COOKIE
get_signed_cookie("user",salt="S8",max_age=None) :Django的加鹽機制,加密,解密都需要加鹽
一下文章轉自:http://www.cnblogs.com/liwenzhou/p/8343243.html
Django中操作Cookie
獲取Cookie
request.COOKIES[‘key‘] request.get_signed_cookie(key, default=RAISE_ERROR, salt=‘‘, max_age=None)
參數:
- default: 默認值
- salt: 加密鹽
- max_age: 後臺控制過期時間
設置Cookie
rep = HttpResponse(...) rep = render(request, ...) 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.) / datetime.now + datetim.timedela(seconds=10) 現在時間 加上失效的時間
- path=‘/‘, Cookie生效的路徑,/ 表示根路徑,特殊的:根路徑的cookie可以被任何url的頁面訪問
- domain=None, Cookie生效的域名
- secure=False, https傳輸
- httponly=False 只能http協議傳輸,無法被JavaScript獲取(不是絕對,底層抓包可以獲取到也可以被覆蓋)
set_cookie源碼:
def set_cookie(self, key, value=‘‘, max_age=None, expires=None, path=‘/‘, domain=None, secure=False, httponly=False):
由於cookie保存在客戶端的電腦上,所以,JavaScript和jquery也可以操作cookie。
<script src=‘/static/js/jquery.cookie.js‘></script> $.cookie("list_pager_num", 30,{ path: ‘/‘ });
刪除Cookie
def logout(request): rep = redirect("/login/") rep.delete_cookie("user") # 刪除用戶瀏覽器上之前設置的usercookie值 return rep
Cookie版登陸校驗
def check_login(func): @wraps(func) def inner(request, *args, **kwargs): next_url = request.get_full_path() if request.get_signed_cookie("login", salt="SSS", default=None) == "yes": # 已經登錄的用戶... return func(request, *args, **kwargs) else: # 沒有登錄的用戶,跳轉剛到登錄頁面 return redirect("/login/?next={}".format(next_url)) return inner def login(request): if request.method == "POST": username = request.POST.get("username") passwd = request.POST.get("password") if username == "xxx" and passwd == "dashabi": next_url = request.GET.get("next") if next_url and next_url != "/logout/": response = redirect(next_url) else: response = redirect("/class_list/") response.set_signed_cookie("login", "yes", salt="SSS") return response return render(request, "login.html")cookie版登錄
進階版 CBV
from django.utils.decorators import method_decorator class IndexView(View): # CBV中最先執行的是dispath方法, # @method_decorator(wrapper) # 這麽寫所有的請求方法都要做登錄校驗 def dispatch(self, request, *args, **kwargs): return super(IndexView, self).dispatch( request, *args, **kwargs) @method_decorator(wrapper) def get(self, request): user = request.session.get("user2", "遊客") return render(request, "index3.html", {"user": user})CBV
Session
Django中默認支持Session,其內部提供了5種類型的Session供開發者使用:
- 數據庫(默認)
- 緩存
- 文件
- 緩存+數據庫
- 加密cookie
同一個人session設置多個key和value,在數據庫中只保存一個記錄,多個key和value hash一次,再次取出時,會解析出來,一個大字典,裏面包含key,value
數據庫Session
SESSION_ENGINE = ‘django.contrib.sessions.backends.db‘ # 引擎(默認)
緩存Session :應用場景 購物車
SESSION_ENGINE = ‘django.contrib.sessions.backends.cache‘ # 引擎 SESSION_CACHE_ALIAS = ‘default‘ # 使用的緩存別名(默認內存緩存,也可以是memcache),此處別名依賴緩存的設置
文件Session
SESSION_ENGINE = ‘django.contrib.sessions.backends.file‘ # 引擎 SESSION_FILE_PATH = None # 緩存文件路徑,如果為None,則使用tempfile模塊獲取一個臨時地址tempfile.gettempdir()
緩存+數據庫:
SESSION_ENGINE = ‘django.contrib.sessions.backends.cached_db‘ # 引擎
加密Cookie Session
SESSION_ENGINE = ‘django.contrib.sessions.backends.signed_cookies‘ # 引擎
其他公用設置項:
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,使用方式都一樣:
def index(request): # 獲取、設置、刪除Session中數據 request.session[‘k1‘] request.session.get(‘k1‘,None) request.session[‘k1‘] = 123 request.session.setdefault(‘k1‘,123) # 存在則不設置 del request.session[‘k1‘] # 所有 鍵、值、鍵值對 request.session.keys() request.session.values() request.session.items() request.session.iterkeys() request.session.itervalues() request.session.iteritems() # 用戶session的隨機字符串 request.session.session_key # 將所有Session失效日期小於當前日期的數據刪除 request.session.clear_expired() # 檢查 用戶session的隨機字符串 在數據庫中是否 request.session.exists("session_key") # 刪除當前用戶的所有Session數據 request.session.delete("session_key") request.session.set_expiry(value) * 如果value是個整數,session會在些秒數後失效。 * 如果value是個datatime或timedelta,session就會在這個時間後失效。 * 如果value是0,用戶關閉瀏覽器session就會失效。 * 如果value是None,session會依賴全局session失效策略。
Session版登陸驗證
from functools import wraps def check_login(func): @wraps(func) def inner(request, *args, **kwargs): next_url = request.get_full_path() if request.session.get("user"): return func(request, *args, **kwargs) else: return redirect("/login/?next={}".format(next_url)) return inner def login(request): if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") if user == "alex" and pwd == "alex1234": # 設置session request.session["user"] = user # 獲取跳到登陸頁面之前的URL next_url = request.GET.get("next") # 如果有,就跳轉回登陸之前的URL if next_url: return redirect(next_url) # 否則默認跳轉到index頁面 else: return redirect("/index/") return render(request, "login.html") @check_login def logout(request): # 刪除所有當前請求相關的session request.session.delete() return redirect("/login/") @check_login def index(request): current_user = request.session.get("user", None) return render(request, "index.html", {"user": current_user})Session版登錄驗證
CBV中加裝飾器相關
CBV實現的登錄視圖
class LoginView(View): def get(self, request): """ 處理GET請求 """ return render(request, ‘login.html‘) def post(self, request): """ 處理POST請求 """ user = request.POST.get(‘user‘) pwd = request.POST.get(‘pwd‘) if user == ‘alex‘ and pwd == "alex1234": next_url = request.GET.get("next") # 生成隨機字符串 # 寫瀏覽器cookie -> session_id: 隨機字符串 # 寫到服務端session: # { # "隨機字符串": {‘user‘:‘alex‘} # } request.session[‘user‘] = user if next_url: return redirect(next_url) else: return redirect(‘/index/‘) return render(request, ‘login.html‘)
要在CBV視圖中使用我們上面的check_login裝飾器,有以下三種方式:
from django.utils.decorators import method_decorator
1. 加在get或post方法上
class LoginView(View): def dispatch(self, request, *args, **kwargs): return super(LoginView,self).dispatch(request, *args, **kwargs) def get(self,request): return render(request,‘login.html‘) @method_decorator(test) def post(self,request): user = request.POST.get(‘user‘) pwd = request.POST.get(‘pwd‘) if user == ‘alex‘ and pwd == "alex3714": # 生成隨機字符串 # 寫瀏覽器cookie: session_id: 隨機字符串 # 寫到服務端session: # { # "隨機字符串": {‘user_info‘:‘alex} # } request.session[‘user_info‘] = "alex" return redirect(‘/index/‘) return render(request, ‘login.html‘)
2. 加在dispatch方法上
class LoginView(View): @method_decorator(test) def dispatch(self, request, *args, **kwargs): return super(LoginView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, ‘login.html‘) def post(self, request): user = request.POST.get(‘user‘) pwd = request.POST.get(‘pwd‘) if user == ‘alex‘ and pwd == "alex3714": # 生成隨機字符串 # 寫瀏覽器cookie: session_id: 隨機字符串 # 寫到服務端session: # { # "隨機字符串": {‘user_info‘:‘alex} # } request.session[‘user_info‘] = "alex" return redirect(‘/index/‘) return render(request, ‘login.html‘)
因為CBV中首先執行的就是dispatch方法,所以這麽寫相當於給get和post方法都加上了登錄校驗。
3. 直接加在視圖類上,但method_decorator必須傳 name 關鍵字參數
如果get方法和post方法都需要登錄校驗的話就寫兩個裝飾器。
from django.utils.decorators import method_decorator @method_decorator(check_login, name="get") @method_decorator(check_login, name="post") class HomeView(View): def dispatch(self, request, *args, **kwargs): return super(HomeView, self).dispatch(request, *args, **kwargs) def get(self, request): return render(request, "home.html") def post(self, request): print("Home View POST method...") return redirect("/index/")
補充
CSRF Token相關裝飾器在CBV只能加到dispatch方法上
備註:
- csrf_protect,為當前函數強制設置防跨站請求偽造功能,即便settings中沒有設置全局中間件。
- csrf_exempt,取消當前函數防跨站請求偽造功能,即便settings中設置了全局中間件。
from django.views.decorators.csrf import csrf_exempt, csrf_protect class LoginView(View): @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): return super(LoginView,self).dispatch(request, *args, **kwargs) def get(self,request): return render(request,‘login.html‘) def post(self,request): user = request.POST.get(‘user‘) pwd = request.POST.get(‘pwd‘) if user == ‘alex‘ and pwd == "alex3714": # 生成隨機字符串 # 寫瀏覽器cookie: session_id: 隨機字符串 # 寫到服務端session: # { # "隨機字符串": {‘user_info‘:‘alex} # } request.session[‘user_info‘] = "alex" return redirect(‘/index/‘) return render(request, ‘login.html‘)
自定義分頁
data = [] for i in range(1, 302): tmp = {"id": i, "name": "alex-{}".format(i)} data.append(tmp) print(data) def user_list(request): # user_list = data[0:10] # user_list = data[10:20] try: current_page = int(request.GET.get("page")) except Exception as e: current_page = 1 per_page = 10 # 數據總條數 total_count = len(data) # 總頁碼 total_page, more = divmod(total_count, per_page) if more: total_page += 1 # 頁面最多顯示多少個頁碼 max_show = 11 half_show = int((max_show-1)/2) if current_page <= half_show: show_start = 1 show_end = max_show else: if current_page + half_show >= total_page: show_start = total_page - max_show show_end = total_page else: show_start = current_page - half_show show_end = current_page + half_show # 數據庫中獲取數據 data_start = (current_page - 1) * per_page data_end = current_page * per_page user_list = data[data_start:data_end] # 生成頁面上顯示的頁碼 page_html_list = [] # 加首頁 first_li = ‘<li><a href="/user_list/?page=1">首頁</a></li>‘ page_html_list.append(first_li) # 加上一頁 if current_page == 1: prev_li = ‘<li><a href="#">上一頁</a></li>‘ else: prev_li = ‘<li><a href="/user_list/?page={}">上一頁</a></li>‘.format(current_page - 1) page_html_list.append(prev_li) for i in range(show_start, show_end+1): if i == current_page: li_tag = ‘<li class="active"><a href="/user_list/?page={0}">{0}</a></li>‘.format(i) else: li_tag = ‘<li><a href="/user_list/?page={0}">{0}</a></li>‘.format(i) page_html_list.append(li_tag) # 加下一頁 if current_page == total_page: next_li = ‘<li><a href="#">下一頁</a></li>‘ else: next_li = ‘<li><a href="/user_list/?page={}">下一頁</a></li>‘.format(current_page+1) page_html_list.append(next_li) # 加尾頁 page_end_li = ‘<li><a href="/user_list/?page={}">尾頁</a></li>‘.format(total_page) page_html_list.append(page_end_li) page_html = "".join(page_html_list) return render(request, "user_list.html", {"user_list": user_list, "page_html": page_html})穩紮穩打版
class Pagination(object): def __init__(self, current_page, total_count, base_url, per_page=10, max_show=11): """ :param current_page: 當前頁 :param total_count: 數據庫中數據總數 :param per_page: 每頁顯示多少條數據 :param max_show: 最多顯示多少頁 """ try: current_page = int(current_page) except Exception as e: current_page = 1 self.current_page = current_page self.total_count = total_count self.base_url = base_url self.per_page = per_page self.max_show = max_show # 總頁碼 total_page, more = divmod(total_count, per_page) if more: total_page += 1 half_show = int((max_show - 1) / 2) self.half_show = half_show self.total_page = total_page @property def start(self): return (self.current_page - 1) * self.per_page @property def end(self): return self.current_page * self.per_page def page_html(self): if self.current_page <= self.half_show: show_start = 1 show_end = self.max_show else: if self.current_page + self.half_show >= self.total_page: show_start = self.total_page - self.max_show show_end = self.total_page else: show_start = self.current_page - self.half_show show_end = self.current_page + self.half_show # 生成頁面上顯示的頁碼 page_html_list = [] # 加首頁 first_li = ‘<li><a href="{}?page=1">首頁</a></li>‘.format(self.base_url) page_html_list.append(first_li) # 加上一頁 if self.current_page == 1: prev_li = ‘<li><a href="#">上一頁</a></li>‘ else: prev_li = ‘<li><a href="{0}?page={1}">上一頁</a></li>‘.format(self.base_url, self.current_page - 1) page_html_list.append(prev_li) for i in range(show_start, show_end + 1): if i == self.current_page: li_tag = ‘<li class="active"><a href="{0}?page={1}">{1}</a></li>‘.format(self.base_url, i) else: li_tag = ‘<li><a href="{0}?page={1}">{1}</a></li>‘.format(self.base_url, i) page_html_list.append(li_tag) # 加下一頁 if self.current_page == self.total_page: next_li = ‘<li><a href="#">下一頁</a></li>‘ else: next_li = ‘<li><a href="{0}?page={1}">下一頁</a></li>‘.format(self.base_url, self.current_page + 1) page_html_list.append(next_li) # 加尾頁 page_end_li = ‘<li><a href="{0}?page={1}">尾頁</a></li>‘.format(self.base_url, self.total_page) page_html_list.append(page_end_li) return "".join(page_html_list) 封裝保存版封裝保存版
def user_list(request): pager = Pagination(request.GET.get("page"), len(data), request.path_info) user_list = data[pager.start:pager.end] page_html = pager.page_html() return render(request, "user_list.html", {"user_list": user_list, "page_html": page_html})封裝保存版使用指南
擴展:
Django內置分頁
from django.shortcuts import render from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger L = [] for i in range(999): L.append(i) def index(request): current_page = request.GET.get(‘p‘) paginator = Paginator(L, 10) # per_page: 每頁顯示條目數量 # count: 數據總個數 # num_pages:總頁數 # page_range:總頁數的索引範圍,如: (1,10),(1,200) # page: page對象 try: posts = paginator.page(current_page) # has_next 是否有下一頁 # next_page_number 下一頁頁碼 # has_previous 是否有上一頁 # previous_page_number 上一頁頁碼 # object_list 分頁之後的數據列表 # number 當前頁 # paginator paginator對象 except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) return render(request, ‘index.html‘, {‘posts‘: posts}) 內置分頁view部分內置分頁view部分
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title></title> </head> <body> <ul> {% for item in posts %} <li>{{ item }}</li> {% endfor %} </ul> <div class="pagination"> <span class="step-links"> {% if posts.has_previous %} <a href="?p={{ posts.previous_page_number }}">Previous</a> {% endif %} <span class="current"> Page {{ posts.number }} of {{ posts.paginator.num_pages }}. </span> {% if posts.has_next %} <a href="?p={{ posts.next_page_number }}">Next</a> {% endif %} </span> </div> </body> </html> 內置分頁HTML部分內置分頁HTML部分
from functools import wraps
wraps:裝飾器修復技術
wraps(func) #取到原來的函數名和說明,不會丟失原來的函數名稱
網址裏面的內容只能從request.GET.get()中取,和
在模板語言中可以使用request
市面上的坐登錄:
加鹽Cookie :數據保存在客戶的瀏覽器上,服務端無壓力
2.Cookie+Session 數據保存在服務端,服務端有一定的數據壓力
SESSION_EXPIRE_AT_BROWSER_CLOSE = False # 是否關閉瀏覽器使得Session過期(默認) SESSION_SAVE_EVERY_REQUEST = True # 是否每次請求都保存Session,默認修改之後才保存(默認)
Django---Cookie && Session