Django中的Session与Cookie
1、相同與不同
Cookie和Session都是為了記錄用戶相關信息的方式,
最大的區別就是Cookie在客戶端記錄而Session在服務端記錄內容。
2、Cookie和Session之間的聯系的建立:
對于Django默認情況來說,當用戶登陸后就可以發現Cookie里油一個sessionid的字段,根據這個key就可以取得在服務端記錄的詳細內容。
如果將這個字段刪除,刷新頁面就會變成未登錄狀態了。
對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_responseengine = import_module(settings.SESSION_ENGINE)self.SessionStore = engine.SessionStoredef 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 thesession every time, save the changes and set a session cookie or deletethe session cookie if the session has been emptied."""try:accessed = request.session.accessedmodified = request.session.modifiedempty = request.session.is_empty()except AttributeError:passelse:# First check if we need to delete this cookie.# The session should be deleted only if the session is entirely emptyif 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 = Noneexpires = Noneelse:max_age = request.session.get_expiry_age()expires_time = time.time() + max_ageexpires = 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 View Code當接收到一個請求的時候,先在Cookie中取出key,然后根據key創建Session對象,在response時候判斷是否要刪除或者修改sessionid。
也就是說,Django中如果客戶把瀏覽器Cookie禁用后,用戶相關的功能就全都失效了,因為服務器端根本沒法知道當前用戶是誰。
對于這種情況,關鍵點就是如何把sessionid不使用Cookie傳遞給客戶端,常見的比如放在URL中,也就是URL重寫技術。想實現這點可以自己寫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.
?
轉載自:https://www.jb51.net/article/119892.htm
?
轉載于:https://www.cnblogs.com/LYliangying/p/9662314.html
總結
以上是生活随笔為你收集整理的Django中的Session与Cookie的全部內容,希望文章能夠幫你解決所遇到的問題。