Django cookie和标题

5 python django cookies


在Django(以及一般情况下),cookie也是一个标题,就像,例如User-Agent
也就是说,这两种方法在Django中是等效的吗?

使用set_cookie:

response.set_cookie('food', 'bread')
response.set_cookie('drink', 'water')
Run Code Online (Sandbox Code Playgroud)

使用标题设置:

response['Cookie'] = ('food=bread; drink=water')
# I'm not sure whether 'Cookie' should be capitalized or not
Run Code Online (Sandbox Code Playgroud)


此外,如果我们可以用第二种方法设置cookie,我们怎么能包括额外的信息,
path,max_age等字符串中?我们要把它们与一些特殊的
角色分开吗?

K Z*_*K Z 5

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

response['Set-Cookie'] = ('food=bread; drink=water; Path=/; max_age=10')
Run Code Online (Sandbox Code Playgroud)

但是,由于Set-Cookieresponse对象中重置将清除前一个,因此Set-CookieDjango中不能有多个头.让我们看看为什么.

观察响应set_cookie .py ,方法:

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
Run Code Online (Sandbox Code Playgroud)

这里值得注意的两件事:

  1. set_cookie方法将为 您处理datetime,expires如果您自己设置,则必须自己设置.
  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=''))))
Run Code Online (Sandbox Code Playgroud)

上面的代码也是为什么在响应头中只set_cookie()允许多个Set-Cookie,并且直接设置cookie到Response对象只会返回一个Set-Cookie.