国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁(yè) > 編程 > Python > 正文

深入探究Django中的Session與Cookie

2020-01-04 17:05:57
字體:
來(lái)源:轉(zhuǎn)載
供稿:網(wǎng)友

前言

Cookie和Session相信對(duì)大家來(lái)說(shuō)并不陌生,簡(jiǎn)單來(lái)說(shuō),Cookie和Session都是為了記錄用戶(hù)相關(guān)信息的方式,最大的區(qū)別就是Cookie在客戶(hù)端記錄而Session在服務(wù)端記錄內(nèi)容。

那么Cookie和Session之間的聯(lián)系是怎么建立的呢?換言之,當(dāng)服務(wù)器接收到一個(gè)請(qǐng)求時(shí)候,根據(jù)什么來(lái)判斷讀取哪個(gè)Session的呢?

對(duì)于Django默認(rèn)情況來(lái)說(shuō),當(dāng)用戶(hù)登錄后就可以發(fā)現(xiàn)Cookie里有一個(gè)sessionid的字段,根據(jù)這個(gè)key就可以取得在服務(wù)器端記錄的詳細(xì)內(nèi)容。如果將這個(gè)字段刪除,刷新頁(yè)面就會(huì)發(fā)現(xiàn)變成未登錄狀態(tài)了。

對(duì)于Session的處理主要在源碼django/contrib/sessions/middleware.py中,如下所示:

import timefrom importlib import import_modulefrom django.conf import settingsfrom django.contrib.sessions.backends.base import UpdateErrorfrom django.core.exceptions import SuspiciousOperationfrom django.utils.cache import patch_vary_headersfrom django.utils.deprecation import MiddlewareMixinfrom django.utils.http import cookie_dateclass 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)接收到一個(gè)請(qǐng)求時(shí)候,先在Cookie里取出key,然后根據(jù)key創(chuàng)建Session對(duì)象,在response時(shí)候判斷是否要?jiǎng)h除或者修改sessionid。

也就是說(shuō),Django中如果客戶(hù)把瀏覽器Cookie禁用后,用戶(hù)相關(guān)的功能就全都失效了,因?yàn)榉?wù)端根本沒(méi)法知道當(dāng)前用戶(hù)是誰(shuí)。

對(duì)于這種情況,關(guān)鍵點(diǎn)就是如何把sessionid不使用Cookie傳遞給客戶(hù)端,常見(jiàn)的比如放在URL中,也就是URL重寫(xiě)技術(shù)。想實(shí)現(xiàn)這點(diǎn)可以自己寫(xiě)Middleware。不過(guò)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é)

以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作能帶來(lái)一定的幫助,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)VEVB武林網(wǎng)的支持

發(fā)表評(píng)論 共有條評(píng)論
用戶(hù)名: 密碼:
驗(yàn)證碼: 匿名發(fā)表
主站蜘蛛池模板: 大悟县| 江陵县| 波密县| 左权县| 东平县| 土默特右旗| 军事| 茶陵县| 长丰县| 三穗县| 孝昌县| 武穴市| 南康市| 宣恩县| 修武县| 永修县| 虎林市| 高邑县| 镇康县| 虹口区| 华宁县| 凤城市| 从江县| 鹰潭市| 商河县| 甘德县| 柘荣县| 关岭| 响水县| 锦州市| 天水市| 唐海县| 习水县| 台江县| 海宁市| 乐清市| 天峨县| 霍城县| 阿拉善左旗| 西乡县| 南投县|