上一章对django的HttpResponse的源码进行分析,对上一篇存在的cookie源码问题,用这篇博客进行分析,若想看关于HttpResponse详解的可点击django模块http之HttpResponse源码解析,
附上http下cookie.py的全部内容,源码下载地址还是在这里,3.0.x,django源码
from http import cookies
# For backwards compatibility in Django 2.1.
SimpleCookie = cookies.SimpleCookie
# Add support for the SameSite attribute (obsolete when PY37 is unsupported).
cookies.Morsel._reserved.setdefault('samesite', 'SameSite')
def parse_cookie(cookie):
"""
Return a dictionary parsed from a `Cookie:` header string.
"""
cookiedict = {}
for chunk in cookie.split(';'):
if '=' in chunk:
key, val = chunk.split('=', 1)
else:
# Assume an empty name per
# https://bugzilla.mozilla.org/show_bug.cgi?id=169091
key, val = '', chunk
key, val = key.strip(), val.strip()
if key or val:
# unquote using Python's algorithm.
cookiedict[key] = cookies._unquote(val)
return cookiedict
- 导入http的cookies这里无法追踪到cookies源码大概查了一些资料Python3标准库:http.cookies HTTP cookie
- 使用cookies.SimpleCookie创建对象,用SimpleCookie进行接收,也就是之后导入该文件可以直接导入SimpleCookie进行使用
- 翻译# Add support for the SameSite attribute (obsolete when PY37 is unsupported).
#添加对SameSite属性的支持(当PY37不被支持时作废)。
cookies.Morsel._reserved.setdefault(‘samesite’, ‘SameSite’)
大概是源码中可以根据python版本进行属性支持和设置,这里查不到源码(记注1) - parse_cookie函数中的注释:Return a dictionary parsed from a
Cookie:
header string,
返回一个从’ Cookie: '头字符串解析的字典这里具体的数据生成,之后运行试试是否能得到结果和这个函数用法(记注2)
下图为parse_cookie函数对cookie数据进行处理的解析说明。
下面代码是HttpResponseBase中的操作cookie的方法也是HttpResponseBase源码解析博客中未解决的位置,现在来看。
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
domain=None, secure=False, httponly=False, samesite=None):
"""
Set a cookie.
``expires`` can be:
- a string in the correct format,
- a naive ``datetime.datetime`` object in UTC,
- an aware ``datetime.datetime`` object in any time zone.
If it is a ``datetime.datetime`` object then calculate ``max_age``.
"""
self.cookies[key] = value
if expires is not None:
if isinstance(expires, datetime.datetime):
if timezone.is_aware(expires):
expires = timezone.make_naive(expires, timezone.utc)
delta = expires - expires.utcnow()
# Add one second so the date matches exactly (a fraction of
# time gets lost between converting to a timedelta and
# then the date string).
delta = delta + datetime.timedelta(seconds=1)
# Just set max_age - the max_age logic will set expires.
expires = None
max_age = max(0, delta.days * 86400 + delta.seconds)
else:
self.cookies[key]['expires'] = expires
else:
self.cookies[key]['expires'] = ''
if max_age is not None:
self.cookies[key]['max-age'] = max_age
# IE requires expires, so set it if hasn't been already.
if not expires:
self.cookies[key]['expires'] = http_date(time.time() + max_age)
if path is not None:
self.cookies[key]['path'] = path
if domain is not None:
self.cookies[key]['domain'] = domain
if secure:
self.cookies[key]['secure'] = True
if httponly:
self.cookies[key]['httponly'] = True
if samesite:
if samesite.lower() not in ('lax', 'strict'):
raise ValueError('samesite must be "lax" or "strict".')
self.cookies[key]['samesite'] = samesite
def setdefault(self, key, value):
"""Set a header unless it has already been set."""
if key not in self:
self[key] = value
def set_signed_cookie(self, key, value, salt='', **kwargs):
value = signing.get_cookie_signer(salt=key + salt).sign(value)
return self.set_cookie(key, value, **kwargs)
def delete_cookie(self, key, path='/', domain=None, samesite=None):
# Most browsers ignore the Set-Cookie header if the cookie name starts
# with __Host- or __Secure- and the cookie doesn't use the secure flag.
secure = key.startswith(('__Secure-', '__Host-'))
self.set_cookie(
key, max_age=0, path=path, domain=domain, secure=secure,
expires='Thu, 01 Jan 1970 00:00:00 GMT', samesite=samesite,
)
源码中包含设置cookie,删除cookie等主要对cookie的操作!