Django Cookies and Headers


In Django (and generally), is a cookie also a header, just like, for example User-Agent,?
That is, are these two methods equivalent in Django?

Usage set_cookie:

response.set_cookie('food', 'bread')
response.set_cookie('drink', 'water')

Using the header setting:

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


In addition, if we can set a cookie using the second method, how can we include additional information,
for example path, max_ageetc. in line? Will we share them with a special character?

+5
source share
3 answers

It would be much easier to use set_cookie. But yes, you can set the cookie to adjust the response header:

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

, Set-Cookie response , Set-Cookie Django. .

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 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 datetime expires , , .
  • 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.

+3

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'].

+1

, "Cookie" "Set-Cookie" "Path =/", .

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

Edit:

After I tried this, I found an interesting quirk, set_cookienot grouping the same cookies (same path, expiration date, domain, etc.) in the same header. It simply adds another “Set-Cookie” to the response. It’s clear that checking and messing with strings will probably take longer than having a few extra bytes in the HTTP headers (and at best it will be micro-optimization).

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=/
0
source

All Articles