python – Django cookie和标题
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了python – Django cookie和标题,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含3488字,纯文字阅读大概需要5分钟。
内容图文
![python – Django cookie和标题](/upload/InfoBanner/zyjiaocheng/826/63e2ecc283d04c749867af5a2327e456.jpg)
在Django(以及一般情况下),cookie也是一个标题,就像,例如用户代理?
也就是说,这两种方法在Django中是等效的吗?
使用set_cookie:
response.set_cookie('food', 'bread')
response.set_cookie('drink', 'water')
使用标题设置:
response['Cookie'] = ('food=bread; drink=water')
# I'm not sure whether 'Cookie' should be capitalized or not
另外,如果我们可以使用第二种方式设置cookie,我们如何包含其他信息,
像字符串中的path,max_age等?我们应该把它们分开一些特别的东西
字符?
解决方法:
如果你使用set_cookie会更容易.但是,是的,你可以设置cookie
设置响应头:
response['Set-Cookie'] = ('food=bread; drink=water; Path=/; max_age=10')
但是,由于在响应对象中重置Set-Cookie将清除之前的内容
一,Django中不能有多个Set-Cookie头.让我们来看看
为什么.
观察response.py, set_cookie method:
class HttpResponseBase:
def __init__(self, content_type=None, status=None, mimetype=None):
# _headers is a mapping of the lower-case name to the original case of
# the header (required for working with legacy systems) and the header
# value. Both the name of the header and its value are ASCII strings.
self._headers = {}
self._charset = settings.DEFAULT_CHARSET
self._closable_objects = []
# This parameter is set by the handler. It's necessary to preserve the
# historical behavior of request_finished.
self._handler_class = None
if mimetype:
warnings.warn("Using mimetype keyword argument is deprecated, use"
" content_type instead",
DeprecationWarning, stacklevel=2)
content_type = mimetype
if not content_type:
content_type = "%s; charset=%s" % (settings.DEFAULT_CONTENT_TYPE,
self._charset)
self.cookies = SimpleCookie()
if status:
self.status_code = status
self['Content-Type'] = content_type
...
def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
domain=None, secure=False, httponly=False):
"""
Sets 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 ``max_age`` will be calculated.
"""
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
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'] = cookie_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
这里值得注意的两件事:
> set_cookie方法将负责处理到期日期
对你而言,如果你自己设置它,你必须自己设置它.
> self.cookie是一本字典词典.所以每个键都会在标题中添加一个[“Set-Cookie”],您很快就会看到.
然后,HttpResponse中的cookie对象将被传递给
WSGIHandler,并附加到响应头:
response_headers = [(str(k), str(v)) for k, v in response.items()]
for c in response.cookies.values():
response_headers.append((str('Set-Cookie'), str(c.output(header=''))))
上面的代码也是为什么只有set_cookie()在响应头中允许多个Set-Cookie,并且将cookie直接设置到Response对象只会返回一个Set-Cookie.
内容总结
以上是互联网集市为您收集整理的python – Django cookie和标题全部内容,希望文章能够帮你解决python – Django cookie和标题所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。