Django cookie和标题

时间:2013-02-27 23:08:17

标签: python django cookies


在Django(以及一般情况下),cookie也是一个标题,就像,例如User-Agent
也就是说,这两种方法在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,我们如何包含其他信息,
比如字符串中的pathmax_age等?我们应该用一些特别的东西将它们分开 人物?

3 个答案:

答案 0 :(得分:5)

使用set_cookie会更容易。但是,是的,你可以设置cookie 设置响应标头:

response['Set-Cookie'] = ('food=bread; drink=water; Path=/; max_age=10')

但是,由于重置Set-Cookie对象中的response将清除之前的内容 一,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

这里值得注意的两件事:

  1. set_cookie方法将负责处理datetime中的expires 对你而言,如果你自己设置它,你必须自己设置它。
  2. self.cookie是一本字典词典。因此,每个key会在标题中添加["Set-Cookie"],您很快就会看到。
  3. 然后cookies内的HttpResponse对象将被传递给 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。{0}}

答案 1 :(得分:1)

HttpResponse 类代码中的代码段:

class HttpResponse(object):

    #...

    def __init__(self, content='', mimetype=None, status=None,

        #...

        self.cookies = SimpleCookie()

    #...

    def set_cookie(self, key, value='', max_age=None, expires=None, path='/',
                   domain=None, secure=False, httponly=False):

        self.cookies[key] = value

        #...


也就是说,每当调用response.set_cookie()时,它都会放置一个新的cookie value response.cookies[key]或更改现有值(如果该密钥有一个) 它解释了为什么它设置了多个Set-Cookie标题 我想知道我们如何用response['Set-Cookie']做同样的事情。

答案 2 :(得分:0)

当然,但是将“Cookie”更改为“Set-Cookie”并添加“Path = /”以使其在网站范围内。

response["Set-Cookie"] = "food=bread; drink=water; Path=/"

修改

在我自己尝试之后,我发现了一个有趣的怪癖,set_cookie没有在同一个标​​题中将类似的cookie(相同的路径,过期,域等)组合在一起。它只是在响应中添加了另一个“Set-Cookie”。可以理解,因为检查和弄乱字符串可能比在HTTP标头中有一些额外的字节花费更多的时间(并且最好是微优化)。

response.set_cookie("food",  "kabanosy")
response.set_cookie("drink", "ardbeg")
response.set_cookie("state", "awesome")

# result in these headers
#   Set-Cookie: food=kabonosy; Path=/
#   Set-Cookie: drink=ardbeg; Path=/
#   Set-Cookie: state=awesome; Path=/

# not this
#   Set-Cookie:food=kabanosy; drink=ardbeg; state=awesome; Path=/