http.cookies.rst 8.57 KB
Newer Older
1 2
:mod:`http.cookies` --- HTTP state management
=============================================
3

4
.. module:: http.cookies
5
   :synopsis: Support for HTTP state management (cookies).
6

7 8 9
.. moduleauthor:: Timothy O'Malley <timo@alum.mit.edu>
.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>

Raymond Hettinger's avatar
Raymond Hettinger committed
10 11 12
**Source code:** :source:`Lib/http/cookies.py`

--------------
13

14
The :mod:`http.cookies` module defines classes for abstracting the concept of
15 16 17 18 19 20
cookies, an HTTP state management mechanism. It supports both simple string-only
cookies, and provides an abstraction for having any serializable data-type as
cookie value.

The module formerly strictly applied the parsing rules described in the
:rfc:`2109` and :rfc:`2068` specifications.  It has since been discovered that
21 22 23 24 25 26 27 28 29 30 31
MSIE 3.0x doesn't follow the character rules outlined in those specs and also
many current day browsers and servers have relaxed parsing rules when comes to
Cookie handling.  As a result, the parsing rules used are a bit less strict.

The character set, :data:`string.ascii_letters`, :data:`string.digits` and
``!#$%&'*+-.^_`|~:`` denote the set of valid characters allowed by this module
in Cookie name (as :attr:`~Morsel.key`).

.. versionchanged:: 3.3
   Allowed ':' as a valid Cookie name character.

32

Georg Brandl's avatar
Georg Brandl committed
33 34 35 36 37 38
.. note::

   On encountering an invalid cookie, :exc:`CookieError` is raised, so if your
   cookie data comes from a browser you should always prepare for invalid data
   and catch :exc:`CookieError` on parsing.

39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62

.. exception:: CookieError

   Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
   incorrect :mailheader:`Set-Cookie` header, etc.


.. class:: BaseCookie([input])

   This class is a dictionary-like object whose keys are strings and whose values
   are :class:`Morsel` instances. Note that upon setting a key to a value, the
   value is first converted to a :class:`Morsel` containing the key and the value.

   If *input* is given, it is passed to the :meth:`load` method.


.. class:: SimpleCookie([input])

   This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
   and :meth:`value_encode` to be the identity and :func:`str` respectively.


.. seealso::

63 64 65
   Module :mod:`http.cookiejar`
      HTTP cookie handling for web *clients*.  The :mod:`http.cookiejar` and
      :mod:`http.cookies` modules do not depend on each other.
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87

   :rfc:`2109` - HTTP State Management Mechanism
      This is the state management specification implemented by this module.


.. _cookie-objects:

Cookie Objects
--------------


.. method:: BaseCookie.value_decode(val)

   Return a decoded value from a string representation. Return value can be any
   type. This method does nothing in :class:`BaseCookie` --- it exists so it can be
   overridden.


.. method:: BaseCookie.value_encode(val)

   Return an encoded value. *val* can be any type, but return value must be a
   string. This method does nothing in :class:`BaseCookie` --- it exists so it can
88
   be overridden.
89 90 91 92 93

   In general, it should be the case that :meth:`value_encode` and
   :meth:`value_decode` are inverses on the range of *value_decode*.


94
.. method:: BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\\r\\n')
95 96 97 98 99 100 101

   Return a string representation suitable to be sent as HTTP headers. *attrs* and
   *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used
   to join the headers together, and is by default the combination ``'\r\n'``
   (CRLF).


102
.. method:: BaseCookie.js_output(attrs=None)
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124

   Return an embeddable JavaScript snippet, which, if run on a browser which
   supports JavaScript, will act the same as if the HTTP headers was sent.

   The meaning for *attrs* is the same as in :meth:`output`.


.. method:: BaseCookie.load(rawdata)

   If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
   found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::

      for k, v in rawdata.items():
          cookie[k] = v


.. _morsel-objects:

Morsel Objects
--------------


125
.. class:: Morsel
126 127 128 129 130 131 132 133 134 135 136 137 138

   Abstract a key/value pair, which has some :rfc:`2109` attributes.

   Morsels are dictionary-like objects, whose set of keys is constant --- the valid
   :rfc:`2109` attributes, which are

   * ``expires``
   * ``path``
   * ``comment``
   * ``domain``
   * ``max-age``
   * ``secure``
   * ``version``
139
   * ``httponly``
140
   * ``samesite``
141

Georg Brandl's avatar
Georg Brandl committed
142
   The attribute :attr:`httponly` specifies that the cookie is only transferred
143 144
   in HTTP requests, and is not accessible through JavaScript. This is intended
   to mitigate some forms of cross-site scripting.
145

146 147 148 149
   The attribute :attr:`samesite` specifies that the browser is not allowed to
   send the cookie along with cross-site requests. This helps to mitigate CSRF
   attacks. Valid values for this attribute are "Strict" and "Lax".

150
   The keys are case-insensitive and their default value is ``''``.
151

152 153 154 155
   .. versionchanged:: 3.5
      :meth:`~Morsel.__eq__` now takes :attr:`~Morsel.key` and :attr:`~Morsel.value`
      into account.

156 157 158 159 160
   .. versionchanged:: 3.7
      Attributes :attr:`~Morsel.key`, :attr:`~Morsel.value` and
      :attr:`~Morsel.coded_value` are read-only.  Use :meth:`~Morsel.set` for
      setting them.

161 162 163
   .. versionchanged:: 3.8
      Added support for the :attr:`samesite` attribute.

164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181

.. attribute:: Morsel.value

   The value of the cookie.


.. attribute:: Morsel.coded_value

   The encoded value of the cookie --- this is what should be sent.


.. attribute:: Morsel.key

   The name of the cookie.


.. method:: Morsel.set(key, value, coded_value)

182
   Set the *key*, *value* and *coded_value* attributes.
183 184 185 186 187 188 189


.. method:: Morsel.isReservedKey(K)

   Whether *K* is a member of the set of keys of a :class:`Morsel`.


190
.. method:: Morsel.output(attrs=None, header='Set-Cookie:')
191 192 193 194 195 196 197

   Return a string representation of the Morsel, suitable to be sent as an HTTP
   header. By default, all the attributes are included, unless *attrs* is given, in
   which case it should be a list of attributes to use. *header* is by default
   ``"Set-Cookie:"``.


198
.. method:: Morsel.js_output(attrs=None)
199 200 201 202 203 204 205

   Return an embeddable JavaScript snippet, which, if run on a browser which
   supports JavaScript, will act the same as if the HTTP header was sent.

   The meaning for *attrs* is the same as in :meth:`output`.


206
.. method:: Morsel.OutputString(attrs=None)
207 208 209 210 211 212 213

   Return a string representing the Morsel, without any surrounding HTTP or
   JavaScript.

   The meaning for *attrs* is the same as in :meth:`output`.


214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231
.. method:: Morsel.update(values)

   Update the values in the Morsel dictionary with the values in the dictionary
   *values*.  Raise an error if any of the keys in the *values* dict is not a
   valid :rfc:`2109` attribute.

   .. versionchanged:: 3.5
      an error is raised for invalid keys.


.. method:: Morsel.copy(value)

   Return a shallow copy of the Morsel object.

   .. versionchanged:: 3.5
      return a Morsel object instead of a dict.


232 233 234 235 236 237
.. method:: Morsel.setdefault(key, value=None)

   Raise an error if key is not a valid :rfc:`2109` attribute, otherwise
   behave the same as :meth:`dict.setdefault`.


238 239 240 241 242
.. _cookie-example:

Example
-------

243
The following example demonstrates how to use the :mod:`http.cookies` module.
Christian Heimes's avatar
Christian Heimes committed
244 245 246

.. doctest::
   :options: +NORMALIZE_WHITESPACE
247

248 249
   >>> from http import cookies
   >>> C = cookies.SimpleCookie()
250 251
   >>> C["fig"] = "newton"
   >>> C["sugar"] = "wafer"
252
   >>> print(C) # generate HTTP headers
253 254
   Set-Cookie: fig=newton
   Set-Cookie: sugar=wafer
Christian Heimes's avatar
Christian Heimes committed
255
   >>> print(C.output()) # same thing
256
   Set-Cookie: fig=newton
Christian Heimes's avatar
Christian Heimes committed
257
   Set-Cookie: sugar=wafer
258
   >>> C = cookies.SimpleCookie()
259 260
   >>> C["rocky"] = "road"
   >>> C["rocky"]["path"] = "/cookie"
261
   >>> print(C.output(header="Cookie:"))
262
   Cookie: rocky=road; Path=/cookie
263
   >>> print(C.output(attrs=[], header="Cookie:"))
264
   Cookie: rocky=road
265
   >>> C = cookies.SimpleCookie()
266
   >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
267
   >>> print(C)
268
   Set-Cookie: chips=ahoy
Christian Heimes's avatar
Christian Heimes committed
269
   Set-Cookie: vienna=finger
270
   >>> C = cookies.SimpleCookie()
271
   >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
272
   >>> print(C)
273
   Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
274
   >>> C = cookies.SimpleCookie()
275 276
   >>> C["oreo"] = "doublestuff"
   >>> C["oreo"]["path"] = "/"
277
   >>> print(C)
278
   Set-Cookie: oreo=doublestuff; Path=/
279
   >>> C = cookies.SimpleCookie()
280 281 282
   >>> C["twix"] = "none for you"
   >>> C["twix"].value
   'none for you'
283
   >>> C = cookies.SimpleCookie()
284 285 286 287 288 289
   >>> C["number"] = 7 # equivalent to C["number"] = str(7)
   >>> C["string"] = "seven"
   >>> C["number"].value
   '7'
   >>> C["string"].value
   'seven'
290
   >>> print(C)
291 292
   Set-Cookie: number=7
   Set-Cookie: string=seven