深入探究Django中的Session與Cookie
前言
Cookie和Session相信對大家來說并不陌生,簡單來說,Cookie和Session都是為了記錄用戶相關(guān)信息的方式,最大的區(qū)別就是Cookie在客戶端記錄而Session在服務(wù)端記錄內(nèi)容。
那么Cookie和Session之間的聯(lián)系是怎么建立的呢?換言之,當服務(wù)器接收到一個請求時候,根據(jù)什么來判斷讀取哪個Session的呢?
對于Django默認情況來說,當用戶登錄后就可以發(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
當接收到一個請求時候,先在Cookie里取出key,然后根據(jù)key創(chuàng)建Session對象,在response時候判斷是否要刪除或者修改sessionid。
也就是說,Django中如果客戶把瀏覽器Cookie禁用后,用戶相關(guān)的功能就全都失效了,因為服務(wù)端根本沒法知道當前用戶是誰。
對于這種情況,關(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)容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家對腳本之家的支持
相關(guān)文章
詳解從Django Allauth中進行登錄改造小結(jié)
這篇文章主要介紹了從 Django Allauth 中進行登錄改造小結(jié),文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-12-12
python pip配置國內(nèi)鏡像源的方法(永久和臨時)
在使用 pip 安裝 Python 模塊時,默認的國外鏡像源可能會導致下載速度緩慢甚至超時,為了解決這個問題,可以使用國內(nèi)的鏡像源來加速下載,以下是常用的國內(nèi)鏡像源以及臨時和永久的配置方法,需要的朋友可以參考下2025-04-04
Python中函數(shù)參數(shù)設(shè)置及使用的學習筆記
這篇文章主要介紹了Python中函數(shù)參數(shù)設(shè)置及使用的學習筆記,記錄了一些Python2.x與Python3.x中函數(shù)參數(shù)相關(guān)的不同點,需要的朋友可以參考下2016-05-05

