| 1 |
:mod:`!http.cookies` --- HTTP state management |
| 2 |
============================================== |
| 3 |
|
| 4 |
.. module:: http.cookies |
| 5 |
:synopsis: Support for HTTP state management (cookies). |
| 6 |
|
| 7 |
.. moduleauthor:: Timothy O'Malley <[email protected]> |
| 8 |
.. sectionauthor:: Moshe Zadka <[email protected]> |
| 9 |
|
| 10 |
**Source code:** :source:`Lib/http/cookies.py` |
| 11 |
|
| 12 |
-------------- |
| 13 |
|
| 14 |
The :mod:`!http.cookies` module defines classes for abstracting the concept of |
| 15 |
cookies, an HTTP state management mechanism. It supports both simple string-only |
| 16 |
cookies, and provides an abstraction for having any serializable data-type as |
| 17 |
cookie value. |
| 18 |
|
| 19 |
The module formerly strictly applied the parsing rules described in the |
| 20 |
:rfc:`2109` and :rfc:`2068` specifications. It has since been discovered that |
| 21 |
MSIE 3.0x didn't follow the character rules outlined in those specs; many |
| 22 |
current-day browsers and servers have also relaxed parsing rules when it comes |
| 23 |
to cookie handling. As a result, this module now uses parsing rules that are a |
| 24 |
bit less strict than they once were. |
| 25 |
|
| 26 |
The character set, :data:`string.ascii_letters`, :data:`string.digits` and |
| 27 |
``!#$%&'*+-.^_`|~:`` denote the set of valid characters allowed by this module |
| 28 |
in a cookie name (as :attr:`~Morsel.key`). |
| 29 |
|
| 30 |
.. versionchanged:: 3.3 |
| 31 |
Allowed ':' as a valid cookie name character. |
| 32 |
|
| 33 |
|
| 34 |
.. note:: |
| 35 |
|
| 36 |
On encountering an invalid cookie, :exc:`CookieError` is raised, so if your |
| 37 |
cookie data comes from a browser you should always prepare for invalid data |
| 38 |
and catch :exc:`CookieError` on parsing. |
| 39 |
|
| 40 |
|
| 41 |
.. exception:: CookieError |
| 42 |
|
| 43 |
Exception failing because of :rfc:`2109` invalidity: incorrect attributes, |
| 44 |
incorrect :mailheader:`Set-Cookie` header, etc. |
| 45 |
|
| 46 |
|
| 47 |
.. class:: BaseCookie([input]) |
| 48 |
|
| 49 |
This class is a dictionary-like object whose keys are strings and whose values |
| 50 |
are :class:`Morsel` instances. Note that upon setting a key to a value, the |
| 51 |
value is first converted to a :class:`Morsel` containing the key and the value. |
| 52 |
|
| 53 |
If *input* is given, it is passed to the :meth:`load` method. |
| 54 |
|
| 55 |
|
| 56 |
.. class:: SimpleCookie([input]) |
| 57 |
|
| 58 |
This class derives from :class:`BaseCookie` and overrides :meth:`~BaseCookie.value_decode` |
| 59 |
and :meth:`~BaseCookie.value_encode`. :class:`!SimpleCookie` supports |
| 60 |
strings as cookie values. When setting the value, :class:`!SimpleCookie` |
| 61 |
calls the builtin :func:`str` to convert |
| 62 |
the value to a string. Values received from HTTP are kept as strings. |
| 63 |
|
| 64 |
.. seealso:: |
| 65 |
|
| 66 |
Module :mod:`http.cookiejar` |
| 67 |
HTTP cookie handling for web *clients*. The :mod:`http.cookiejar` and |
| 68 |
:mod:`!http.cookies` modules do not depend on each other. |
| 69 |
|
| 70 |
:rfc:`2109` - HTTP State Management Mechanism |
| 71 |
This is the state management specification implemented by this module. |
| 72 |
|
| 73 |
|
| 74 |
.. _cookie-objects: |
| 75 |
|
| 76 |
Cookie Objects |
| 77 |
-------------- |
| 78 |
|
| 79 |
|
| 80 |
.. method:: BaseCookie.value_decode(val) |
| 81 |
|
| 82 |
Return a tuple ``(real_value, coded_value)`` from a string representation. |
| 83 |
``real_value`` can be any type. This method does no decoding in |
| 84 |
:class:`BaseCookie` --- it exists so it can be overridden. |
| 85 |
|
| 86 |
|
| 87 |
.. method:: BaseCookie.value_encode(val) |
| 88 |
|
| 89 |
Return a tuple ``(real_value, coded_value)``. *val* can be any type, but |
| 90 |
``coded_value`` will always be converted to a string. |
| 91 |
This method does no encoding in :class:`BaseCookie` --- it exists so it can |
| 92 |
be overridden. |
| 93 |
|
| 94 |
In general, it should be the case that :meth:`value_encode` and |
| 95 |
:meth:`value_decode` are inverses on the range of *value_decode*. |
| 96 |
|
| 97 |
|
| 98 |
.. method:: BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\r\n') |
| 99 |
|
| 100 |
Return a string representation suitable to be sent as HTTP headers. *attrs* and |
| 101 |
*header* are sent to each :class:`Morsel`'s :meth:`~Morsel.output` method. *sep* is used |
| 102 |
to join the headers together, and is by default the combination ``'\r\n'`` |
| 103 |
(CRLF). |
| 104 |
|
| 105 |
|
| 106 |
.. method:: BaseCookie.js_output(attrs=None) |
| 107 |
|
| 108 |
Return an embeddable JavaScript snippet, which, if run on a browser which |
| 109 |
supports JavaScript, will act the same as if the HTTP headers was sent. |
| 110 |
|
| 111 |
The meaning for *attrs* is the same as in :meth:`output`. |
| 112 |
|
| 113 |
|
| 114 |
.. method:: BaseCookie.load(rawdata) |
| 115 |
|
| 116 |
If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values |
| 117 |
found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to:: |
| 118 |
|
| 119 |
for k, v in rawdata.items(): |
| 120 |
cookie[k] = v |
| 121 |
|
| 122 |
|
| 123 |
.. _morsel-objects: |
| 124 |
|
| 125 |
Morsel Objects |
| 126 |
-------------- |
| 127 |
|
| 128 |
|
| 129 |
.. class:: Morsel |
| 130 |
|
| 131 |
Abstract a key/value pair, which has some :rfc:`2109` attributes. |
| 132 |
|
| 133 |
Morsels are dictionary-like objects, whose set of keys is constant --- the valid |
| 134 |
:rfc:`2109` attributes, which are: |
| 135 |
|
| 136 |
.. attribute:: expires |
| 137 |
path |
| 138 |
comment |
| 139 |
domain |
| 140 |
max-age |
| 141 |
secure |
| 142 |
version |
| 143 |
httponly |
| 144 |
samesite |
| 145 |
partitioned |
| 146 |
|
| 147 |
The attribute :attr:`httponly` specifies that the cookie is only transferred |
| 148 |
in HTTP requests, and is not accessible through JavaScript. This is intended |
| 149 |
to mitigate some forms of cross-site scripting. |
| 150 |
|
| 151 |
The attribute :attr:`samesite` controls when the browser sends the cookie with |
| 152 |
cross-site requests. This helps to mitigate CSRF attacks. Valid values are |
| 153 |
"Strict" (only sent with same-site requests), "Lax" (sent with same-site |
| 154 |
requests and top-level navigations), and "None" (sent with same-site and |
| 155 |
cross-site requests). When using "None", the "secure" attribute must also |
| 156 |
be set, as required by modern browsers. |
| 157 |
|
| 158 |
The attribute :attr:`partitioned` indicates to user agents that these |
| 159 |
cross-site cookies *should* only be available in the same top-level context |
| 160 |
that the cookie was first set in. For this to be accepted by the user agent, |
| 161 |
you **must** also set ``Secure``. |
| 162 |
|
| 163 |
In addition, it is recommended to use the ``__Host`` prefix when setting |
| 164 |
partitioned cookies to make them bound to the hostname and not the |
| 165 |
registrable domain. Read |
| 166 |
`CHIPS (Cookies Having Independent Partitioned State)`_ |
| 167 |
for full details and examples. |
| 168 |
|
| 169 |
.. _CHIPS (Cookies Having Independent Partitioned State): https://github.com/privacycg/CHIPS/blob/main/README.md |
| 170 |
|
| 171 |
The keys are case-insensitive and their default value is ``''``. |
| 172 |
|
| 173 |
.. versionchanged:: 3.5 |
| 174 |
:meth:`!__eq__` now takes :attr:`~Morsel.key` and :attr:`~Morsel.value` |
| 175 |
into account. |
| 176 |
|
| 177 |
.. versionchanged:: 3.7 |
| 178 |
Attributes :attr:`~Morsel.key`, :attr:`~Morsel.value` and |
| 179 |
:attr:`~Morsel.coded_value` are read-only. Use :meth:`~Morsel.set` for |
| 180 |
setting them. |
| 181 |
|
| 182 |
.. versionchanged:: 3.8 |
| 183 |
Added support for the :attr:`samesite` attribute. |
| 184 |
|
| 185 |
.. versionchanged:: 3.14 |
| 186 |
Added support for the :attr:`partitioned` attribute. |
| 187 |
|
| 188 |
|
| 189 |
.. attribute:: Morsel.value |
| 190 |
|
| 191 |
The value of the cookie. |
| 192 |
|
| 193 |
|
| 194 |
.. attribute:: Morsel.coded_value |
| 195 |
|
| 196 |
The encoded value of the cookie --- this is what should be sent. |
| 197 |
|
| 198 |
|
| 199 |
.. attribute:: Morsel.key |
| 200 |
|
| 201 |
The name of the cookie. |
| 202 |
|
| 203 |
|
| 204 |
.. method:: Morsel.set(key, value, coded_value) |
| 205 |
|
| 206 |
Set the *key*, *value* and *coded_value* attributes. |
| 207 |
|
| 208 |
|
| 209 |
.. method:: Morsel.isReservedKey(K) |
| 210 |
|
| 211 |
Whether *K* is a member of the set of keys of a :class:`Morsel`. |
| 212 |
|
| 213 |
|
| 214 |
.. method:: Morsel.output(attrs=None, header='Set-Cookie:') |
| 215 |
|
| 216 |
Return a string representation of the Morsel, suitable to be sent as an HTTP |
| 217 |
header. By default, all the attributes are included, unless *attrs* is given, in |
| 218 |
which case it should be a list of attributes to use. *header* is by default |
| 219 |
``"Set-Cookie:"``. |
| 220 |
|
| 221 |
|
| 222 |
.. method:: Morsel.js_output(attrs=None) |
| 223 |
|
| 224 |
Return an embeddable JavaScript snippet, which, if run on a browser which |
| 225 |
supports JavaScript, will act the same as if the HTTP header was sent. |
| 226 |
|
| 227 |
The meaning for *attrs* is the same as in :meth:`output`. |
| 228 |
|
| 229 |
|
| 230 |
.. method:: Morsel.OutputString(attrs=None) |
| 231 |
|
| 232 |
Return a string representing the Morsel, without any surrounding HTTP or |
| 233 |
JavaScript. |
| 234 |
|
| 235 |
The meaning for *attrs* is the same as in :meth:`output`. |
| 236 |
|
| 237 |
|
| 238 |
.. method:: Morsel.update(values) |
| 239 |
|
| 240 |
Update the values in the Morsel dictionary with the values in the dictionary |
| 241 |
*values*. Raise an error if any of the keys in the *values* dict is not a |
| 242 |
valid :rfc:`2109` attribute. |
| 243 |
|
| 244 |
.. versionchanged:: 3.5 |
| 245 |
an error is raised for invalid keys. |
| 246 |
|
| 247 |
|
| 248 |
.. method:: Morsel.copy(value) |
| 249 |
|
| 250 |
Return a shallow copy of the Morsel object. |
| 251 |
|
| 252 |
.. versionchanged:: 3.5 |
| 253 |
return a Morsel object instead of a dict. |
| 254 |
|
| 255 |
|
| 256 |
.. method:: Morsel.setdefault(key, value=None) |
| 257 |
|
| 258 |
Raise an error if key is not a valid :rfc:`2109` attribute, otherwise |
| 259 |
behave the same as :meth:`dict.setdefault`. |
| 260 |
|
| 261 |
|
| 262 |
.. _cookie-example: |
| 263 |
|
| 264 |
Example |
| 265 |
------- |
| 266 |
|
| 267 |
The following example demonstrates how to use the :mod:`!http.cookies` module. |
| 268 |
|
| 269 |
.. doctest:: |
| 270 |
:options: +NORMALIZE_WHITESPACE |
| 271 |
|
| 272 |
>>> from http import cookies |
| 273 |
>>> C = cookies.SimpleCookie() |
| 274 |
>>> C["fig"] = "newton" |
| 275 |
>>> C["sugar"] = "wafer" |
| 276 |
>>> print(C) # generate HTTP headers |
| 277 |
Set-Cookie: fig=newton |
| 278 |
Set-Cookie: sugar=wafer |
| 279 |
>>> print(C.output()) # same thing |
| 280 |
Set-Cookie: fig=newton |
| 281 |
Set-Cookie: sugar=wafer |
| 282 |
>>> C = cookies.SimpleCookie() |
| 283 |
>>> C["rocky"] = "road" |
| 284 |
>>> C["rocky"]["path"] = "/cookie" |
| 285 |
>>> print(C.output(header="Cookie:")) |
| 286 |
Cookie: rocky=road; Path=/cookie |
| 287 |
>>> print(C.output(attrs=[], header="Cookie:")) |
| 288 |
Cookie: rocky=road |
| 289 |
>>> C = cookies.SimpleCookie() |
| 290 |
>>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header) |
| 291 |
>>> print(C) |
| 292 |
Set-Cookie: chips=ahoy |
| 293 |
Set-Cookie: vienna=finger |
| 294 |
>>> C = cookies.SimpleCookie() |
| 295 |
>>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=;";') |
| 296 |
>>> print(C) |
| 297 |
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=;" |
| 298 |
>>> C = cookies.SimpleCookie() |
| 299 |
>>> C["oreo"] = "doublestuff" |
| 300 |
>>> C["oreo"]["path"] = "/" |
| 301 |
>>> print(C) |
| 302 |
Set-Cookie: oreo=doublestuff; Path=/ |
| 303 |
>>> C = cookies.SimpleCookie() |
| 304 |
>>> C["twix"] = "none for you" |
| 305 |
>>> C["twix"].value |
| 306 |
'none for you' |
| 307 |
>>> C = cookies.SimpleCookie() |
| 308 |
>>> C["number"] = 7 # equivalent to C["number"] = str(7) |
| 309 |
>>> C["string"] = "seven" |
| 310 |
>>> C["number"].value |
| 311 |
'7' |
| 312 |
>>> C["string"].value |
| 313 |
'seven' |
| 314 |
>>> print(C) |
| 315 |
Set-Cookie: number=7 |
| 316 |
Set-Cookie: string=seven |