6


在 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,我们如何在字符串中包含附加信息,
path,max_age等?我们应该用一些特殊
字符将它们分开吗?

4

3 回答 3

7

如果你使用它会容易得多set_cookie。但是是的,您可以通过设置响应标头来设置 cookie:

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

Set-Cookie但是,由于在对象中重置response会清除前一个,因此在 Django 中不能有多个Set-Cookie标题。让我们看看为什么。

在response.py 中set_cookie观察,方法

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方法将为您处理datetimeexpires 如果您自己设置,则必须自己设置。
  2. self.cookie是字典的字典。所以每个key人都会在标题中添加一个["Set-Cookie"],你很快就会看到。

然后里面的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

于 2013-02-28T02:06:00.907 回答
1

当然可以,但是将“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=/
于 2013-02-27T23:18:14.290 回答
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
valueresponse.cookies[key]要么更改现有值(如果该键上有一个)。
它解释了为什么它设置多个Set-Cookie标题。
我想知道我们怎么能用response['Set-Cookie'].

于 2013-02-28T00:36:47.823 回答