Python之路--Django--Cookie、Session和自定義分頁

1、Cookie

一、Cookie的由來

  你們都知道HTTP協議是無狀態的。html

  無狀態的意思是每次請求都是獨立的,它的執行狀況和結果與前面的請求和以後的請求都無直接關係,它不會受前面的請求響應狀況直接影響,也不會直接影響後python

面的請求響應狀況。數據庫

  一句有意思的話來描述就是人生只如初見,對服務器來講,每次的請求都是全新的。django

  狀態能夠理解爲客戶端和服務器在某次會話中產生的數據,那無狀態的就覺得這些數據不會被保留。會話中產生的數據又是咱們須要保存的,也就是說要「保持狀bootstrap

態」。所以Cookie就是在這樣一個場景下誕生。瀏覽器

 

二、什麼是Cookie

  Cookie具體指的是一段小信息,它是服務器發送出來存儲在瀏覽器上的一組組鍵值對,下次訪問服務器時瀏覽器會自動攜帶這些鍵值對,以便服務器提取有用信息。緩存

 

三、Cookie的原理

  Cookie的工做原理是:由服務器產生內容,瀏覽器收到請求後保存在本地;當瀏覽器再次訪問時,瀏覽器會自動帶上Cookie,這樣服務器就能經過Cookie的內容來判斷這個是「誰」了。安全

 

四、查看Cookie

  咱們使用Chrome瀏覽器,打開開發者工具。服務器

 

五、Django中操做Cookie

5.一、獲取Cookie cookie

request.COOKIES['key'] request.get_signed_cookie(key, default=RAISE_ERROR, salt='', max_age=None)

參數:

  • default: 默認值
  • salt: 加密鹽
  • max_age: 後臺控制過時時間

 

5.二、設置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.)
  • path='/', Cookie生效的路徑,/ 表示根路徑,特殊的:根路徑的cookie能夠被任何url的頁面訪問
  • domain=None, Cookie生效的域名
  • secure=False, https傳輸
  • httponly=False 只能http協議傳輸,沒法被JavaScript獲取(不是絕對,底層抓包能夠獲取到也能夠被覆蓋)

 

5.三、刪除Cookie

def logout(request): rep = redirect("/login/") rep.delete_cookie("user")  # 刪除用戶瀏覽器上以前設置的user cookie值
    return rep

 

Cookie版登錄校驗:

from django.shortcuts import render, redirect # Create your views here.
from functools import wraps def check_login(func): @wraps(func) # 裝飾器修復技術
    def inner(request, *args, **kwargs): ret = request.get_signed_cookie("is_login", default="0", salt="s10nb") if ret == "1": # 已經登錄過的 繼續執行
            return func(request, *args, **kwargs) # 沒有登陸過的 跳轉到登陸頁面
        else: # 獲取當前訪問的URL
            next_url = request.path_info print(next_url) return redirect("/login/?next={}".format(next_url)) return inner def login(request): print(request.get_full_path())  # 獲取當前請求的路徑和參數
    print(request.path_info)  # 取當前請求的路徑
    print("-" * 120) if request.method == "POST": user = request.POST.get("user") pwd = request.POST.get("pwd") # 從URL裏面取到 next 參數
        next_url = request.GET.get("next") if user == "alex" and pwd == "dsb": # 登錄成功
            # 告訴瀏覽器保存一個鍵值對

            if next_url: rep = redirect(next_url)  # 獲得一個響應對象
            else: rep = redirect("/home/")  # 獲得一個響應對象

            # rep.set_cookie("is_login", "1")
            # 設置加鹽的cookie
            rep.set_signed_cookie("is_login", "1", salt="s10nb", max_age=10)  # 單位是秒
            return rep return render(request, "login.html") def home(request): # 從請求的cookie中找 有沒有 xiaohei
    # ret = request.COOKIES.get("is_login", 0)
    # 取加鹽過的
    ret = request.get_signed_cookie("is_login", default="0", salt="s10nb") print(ret, type(ret)) if ret == "1": # 表示已經登錄過
        return render(request, "home.html") else: return redirect("/login/") @check_login def index(request): return render(request, "index.html") # 註銷函數
def logout(request): # 如何刪除Cookie
    rep = redirect("/login/") rep.delete_cookie("is_login") return rep

 

2、Session

一、Session的由來

  Cookie雖然在必定程度上解決了「保持狀態」的需求,可是因爲Cookie自己最大支持4096字節,以及Cookie自己保存在客戶端,可能被攔截或竊取,所以就須要有一種新的東西,它能支持更多的字節,而且他保存在服務器,有較高的安全性。這就是Session。

  問題來了,基於HTTP協議的無狀態特徵,服務器根本就不知道訪問者是「誰」。那麼上述的Cookie就起到橋接的做用。

  咱們能夠給每一個客戶端的Cookie分配一個惟一的id,這樣用戶在訪問時,經過Cookie,服務器就知道來的人是「誰」。而後咱們再根據不一樣的Cookie的id,在服務器上保存一段時間的私密資料,如「帳號密碼」等等。

  總結而言:Cookie彌補了HTTP無狀態的不足,讓服務器知道來的人是「誰」;可是Cookie以文本的形式保存在本地,自身安全性較差;因此咱們就經過Cookie識別不一樣的用戶,對應的在Session裏保存私密的信息以及超過4096字節的文本。

  另外,上述所說的Cookie和Session實際上是共通性的東西,不限於語言和框架。

 

二、Django中Session相關方法

# 獲取、設置、刪除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的key
request.session.session_key # 將全部Session失效日期小於當前日期的數據刪除
request.session.clear_expired() # 檢查會話session的key在數據庫中是否存在
request.session.exists("session_key") # 刪除當前會話的全部Session數據
request.session.delete()    # 刪除當前的會話數據並刪除會話的Cookie。
request.session.flush() 這用於確保前面的會話數據不能夠再次被用戶的瀏覽器訪問 例如,django.contrib.auth.logout() 函數中就會調用它。 # 設置會話Session和Cookie的超時時間
request.session.set_expiry(value) * 若是value是個整數,session會在些秒數後失效。 * 若是value是個datatime或timedelta,session就會在這個時間後失效。 * 若是value是0,用戶關閉瀏覽器session就會失效。 * 若是value是None,session會依賴全局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})

 

五、Django中的Session配置

Django中默認支持Session,其內部提供了5種類型的Session供開發者使用。

1. 數據庫Session SESSION_ENGINE = 'django.contrib.sessions.backends.db'   # 引擎(默認)

2. 緩存Session SESSION_ENGINE = 'django.contrib.sessions.backends.cache'  # 引擎
SESSION_CACHE_ALIAS = 'default'                            # 使用的緩存別名(默認內存緩存,也能夠是memcache),此處別名依賴緩存的設置

3. 文件Session SESSION_ENGINE = 'django.contrib.sessions.backends.file'    # 引擎
SESSION_FILE_PATH = None                                    # 緩存文件路徑,若是爲None,則使用tempfile模塊獲取一個臨時地址tempfile.gettempdir() 

4. 緩存+數據庫 SESSION_ENGINE = 'django.contrib.sessions.backends.cached_db'        # 引擎

5. 加密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,默認修改以後才保存(默認)

 

六、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. 加在CBV視圖的get或post方法上

from django.utils.decorators import method_decorator 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") @method_decorator(check_login) def post(self, request): print("Home View POST method...") return redirect("/index/")

 

2. 加在dispatch方法上

from django.utils.decorators import method_decorator class HomeView(View): @method_decorator(check_login) 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/")

由於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_protect,csrf_exempt

CSRF Token相關裝飾器在CBV只能加到dispatch方法上,或者加在視圖類上而後name參數指定爲dispatch方法。

備註:

  • csrf_protect,爲當前函數強制設置防跨站請求僞造功能,即使settings中沒有設置全局中間件。
  • csrf_exempt,取消當前函數防跨站請求僞造功能,即使settings中設置了全局中間件。
from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.utils.decorators import method_decorator class HomeView(View): @method_decorator(csrf_exempt) 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/")

或者

from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.utils.decorators import method_decorator @method_decorator(csrf_exempt, name='dispatch') 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/")

 

3、分頁

一、自定義分頁

終極封裝版:

# !usr/bin/env python  # -*- coding:utf-8 -*-
""" @Author : YangLei (1912739092@qq.com) @file : my_paging.py @time : 2018/07/27 @Link : http://www.cnblogs.com/TuyereIOT/ @Version : """

class Paging(): def __init__(self, page_num, total_count, url_prefix, per_page=10, max_page=11): """ 根據 bootstrap4 定製的分頁組件 :param page_num: 當前頁碼數 :param total_count: 數據總數 :param url_prefix: a標籤href的前綴 :param per_page: 每頁顯示多少條數據 :param max_page: 頁面上最多顯示幾個頁碼 """ self.url_prefix = url_prefix self.max_page = max_page # 每一頁顯示多少條數據
        # 總共須要多少頁碼來展現
        total_page, m = divmod(total_count, per_page) if m: total_page += 1 self.total_page = total_page try: page_num = int(page_num) # 若是輸入的頁碼數超過了最大的頁碼數,默認返回最後一頁
            if page_num > total_page: page_num = total_page except Exception as e: # 當輸入的頁碼不是正經數字的時候 默認返回第一頁的數據
            page_num = 1 self.page_num = page_num # 定義兩個變量保存數據從哪兒取到哪兒
        self.data_start = (page_num - 1) * 10 self.data_end = page_num * 10

        # 頁面上總共展現多少頁碼
        if total_page < self.max_page: self.max_page = total_page half_max_page = self.max_page // 2
        # 頁面上展現的頁碼從哪兒開始
        page_start = page_num - half_max_page # 頁面上展現的頁碼到哪兒結束
        page_end = page_num + half_max_page # 若是當前頁減一半 比1還小
        if page_start <= 1: page_start = 1 page_end = self.max_page # 若是 當前頁 加 一半 比總頁碼數還大
        if page_end >= total_page: page_end = total_page page_start = total_page - self.max_page + 1 self.page_start = page_start self.page_end = page_end @property def start(self): return self.data_start @property def end(self): return self.data_end def page_html(self): # 本身拼接分頁的HTML代碼
        html_str_list = [] # 加上第一頁
 html_str_list.append( '<li class="page-item"><a class="page-link" href="{}?page=1">首頁</a></li>'.format(self.url_prefix)) # 判斷一下 若是是第一頁,就沒有上一頁
        if self.page_num <= 1: html_str_list.append( '<li class="disabled page-item"><a class="page-link" href="#"><span aria-hidden="true">&laquo;</span></a></li>'.format( self.page_num - 1)) else: # 加一個上一頁的標籤
 html_str_list.append( '<li class="page-item"><a class="page-link" href="{}?page={}"><span aria-hidden="true">&laquo;</span></a></li>'.format( self.url_prefix, self.page_num - 1)) for i in range(self.page_start, self.page_end + 1): # 若是是當前頁就加一個active樣式類
            if i == self.page_num: tmp = '<li class="active page-item"><a class="page-link" href="{0}?page={1}">{1}</a></li>'.format( self.url_prefix, i) else: tmp = '<li class="page-item"><a class="page-link" href="{0}?page={1}">{1}</a></li>'.format( self.url_prefix, i) html_str_list.append(tmp) # 加一個下一頁的按鈕
        # 判斷,若是是最後一頁,就沒有下一頁
        if self.page_num >= self.total_page: html_str_list.append( '<li class="disabled page-item"><a class="page-link" href="#"><span aria-hidden="true">&raquo;</span></a></li>') else: html_str_list.append( '<li class="page-item"><a class="page-link" href="{}?page={}"><span aria-hidden="true">&raquo;</span></a></li>'.format( self.url_prefix, self.page_num + 1)) # 加最後一頁
 html_str_list.append( '<li class="page-item"><a class="page-link" href="{}?page={}">尾頁</a></li>'.format(self.url_prefix, self.total_page)) page_html = "".join(html_str_list) return page_html

使用:

def books(request): # 獲取頁碼數
    page_num = request.GET.get("page") # 獲取總數據量
    total_count = models.Book.objects.all().count() # 調用分頁類
    from utils.my_paging import Paging page_obj = Paging(page_num, total_count, url_prefix="/books/", max_page=7) # 將數據切片
    ret = models.Book.objects.all()[page_obj.start:page_obj.end] # 本身拼接分頁HTML代碼
    page_html = page_obj.page_html() return render(request, "app02_session/books.html", {"books": ret, "page_html": page_html})

 

二、Django內置分頁

View.py

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})

html部分

<!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>
相關文章
相關標籤/搜索