深入探究Django中的Session與Cookie
前言
Cookie和Session相信對大家來說并不陌生,簡單來說,Cookie和Session都是為了記錄用戶相關(guān)信息的方式,最大的區(qū)別就是Cookie在客戶端記錄而Session在服務(wù)端記錄內(nèi)容。
那么Cookie和Session之間的聯(lián)系是怎么建立的呢?換言之,當(dāng)服務(wù)器接收到一個請求時候,根據(jù)什么來判斷讀取哪個Session的呢?
對于Django默認情況來說,當(dāng)用戶登錄后就可以發(fā)現(xiàn)Cookie里有一個sessionid的字段,根據(jù)這個key就可以取得在服務(wù)器端記錄的詳細內(nèi)容。如果將這個字段刪除,刷新頁面就會發(fā)現(xiàn)變成未登錄狀態(tài)了。
對于Session的處理主要在源碼django/contrib/sessions/middleware.py中,如下所示:
import time from importlib import import_module from django.conf import settings from django.contrib.sessions.backends.base import UpdateError from django.core.exceptions import SuspiciousOperation from django.utils.cache import patch_vary_headers from django.utils.deprecation import MiddlewareMixin from django.utils.http import cookie_date class SessionMiddleware(MiddlewareMixin): def __init__(self, get_response=None): self.get_response = get_response engine = import_module(settings.SESSION_ENGINE) self.SessionStore = engine.SessionStore def process_request(self, request): session_key = request.COOKIES.get(settings.SESSION_COOKIE_NAME) request.session = self.SessionStore(session_key) def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie or delete the session cookie if the session has been emptied. """ try: accessed = request.session.accessed modified = request.session.modified empty = request.session.is_empty() except AttributeError: pass else: # First check if we need to delete this cookie. # The session should be deleted only if the session is entirely empty if settings.SESSION_COOKIE_NAME in request.COOKIES and empty: response.delete_cookie( settings.SESSION_COOKIE_NAME, path=settings.SESSION_COOKIE_PATH, domain=settings.SESSION_COOKIE_DOMAIN, ) else: if accessed: patch_vary_headers(response, ('Cookie',)) if (modified or settings.SESSION_SAVE_EVERY_REQUEST) and not empty: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = cookie_date(expires_time) # Save the session data and refresh the client cookie. # Skip session save for 500 responses, refs #3881. if response.status_code != 500: try: request.session.save() except UpdateError: raise SuspiciousOperation( "The request's session was deleted before the " "request completed. The user may have logged " "out in a concurrent request, for example." ) response.set_cookie( settings.SESSION_COOKIE_NAME, request.session.session_key, max_age=max_age, expires=expires, domain=settings.SESSION_COOKIE_DOMAIN, path=settings.SESSION_COOKIE_PATH, secure=settings.SESSION_COOKIE_SECURE or None, httponly=settings.SESSION_COOKIE_HTTPONLY or None, ) return response
當(dāng)接收到一個請求時候,先在Cookie里取出key,然后根據(jù)key創(chuàng)建Session對象,在response時候判斷是否要刪除或者修改sessionid。
也就是說,Django中如果客戶把瀏覽器Cookie禁用后,用戶相關(guān)的功能就全都失效了,因為服務(wù)端根本沒法知道當(dāng)前用戶是誰。
對于這種情況,關(guān)鍵點就是如何把sessionid不使用Cookie傳遞給客戶端,常見的比如放在URL中,也就是URL重寫技術(shù)。想實現(xiàn)這點可以自己寫Middleware。不過django并不建議這么做:
The Django sessions framework is entirely, and solely, cookie-based. It does not fall back to putting session IDs in URLs as a last resort, as PHP does. This is an intentional design decision. Not only does that behavior make URLs ugly, it makes your site vulnerable to session-ID theft via the “Referer” header.
總結(jié)
以上就是這篇文章的全部內(nèi)容了,希望本文的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持
相關(guān)文章
Python基于多線程實現(xiàn)抓取數(shù)據(jù)存入數(shù)據(jù)庫的方法
這篇文章主要介紹了Python基于多線程實現(xiàn)抓取數(shù)據(jù)存入數(shù)據(jù)庫的方法,結(jié)合實例形式分析了Python使用數(shù)據(jù)庫類與多線程類進行數(shù)據(jù)抓取與寫入數(shù)據(jù)庫操作的具體使用技巧,需要的朋友可以參考下2018-06-06深入淺析pycharm中 Make available to all projects的含義
這篇文章主要介紹了pycharm中 Make available to all projects的含義,本文給大家介紹的非常詳細,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-09-09