blob: f3457a0cdc7bc48a1f57f1779ec981ab045440a2 [file] [log] [blame]
Georg Brandl24420152008-05-26 16:32:26 +00001:mod:`http.cookies` --- HTTP state management
2=============================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Georg Brandl24420152008-05-26 16:32:26 +00004.. module:: http.cookies
Georg Brandl116aa622007-08-15 14:28:22 +00005 :synopsis: Support for HTTP state management (cookies).
Terry Jan Reedyfa089b92016-06-11 15:02:54 -04006
Georg Brandl116aa622007-08-15 14:28:22 +00007.. moduleauthor:: Timothy O'Malley <timo@alum.mit.edu>
8.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
9
Raymond Hettinger469271d2011-01-27 20:38:46 +000010**Source code:** :source:`Lib/http/cookies.py`
11
12--------------
Georg Brandl116aa622007-08-15 14:28:22 +000013
Georg Brandl24420152008-05-26 16:32:26 +000014The :mod:`http.cookies` module defines classes for abstracting the concept of
Georg Brandl116aa622007-08-15 14:28:22 +000015cookies, an HTTP state management mechanism. It supports both simple string-only
16cookies, and provides an abstraction for having any serializable data-type as
17cookie value.
18
19The module formerly strictly applied the parsing rules described in the
20:rfc:`2109` and :rfc:`2068` specifications. It has since been discovered that
Senthil Kumarandf7070a2012-04-22 10:31:52 +080021MSIE 3.0x doesn't follow the character rules outlined in those specs and also
22many current day browsers and servers have relaxed parsing rules when comes to
23Cookie handling. As a result, the parsing rules used are a bit less strict.
24
25The character set, :data:`string.ascii_letters`, :data:`string.digits` and
26``!#$%&'*+-.^_`|~:`` denote the set of valid characters allowed by this module
27in Cookie name (as :attr:`~Morsel.key`).
28
29.. versionchanged:: 3.3
30 Allowed ':' as a valid Cookie name character.
31
Georg Brandl116aa622007-08-15 14:28:22 +000032
Georg Brandlf08a9dd2008-06-10 16:57:31 +000033.. note::
34
35 On encountering an invalid cookie, :exc:`CookieError` is raised, so if your
36 cookie data comes from a browser you should always prepare for invalid data
37 and catch :exc:`CookieError` on parsing.
38
Georg Brandl116aa622007-08-15 14:28:22 +000039
40.. exception:: CookieError
41
42 Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
43 incorrect :mailheader:`Set-Cookie` header, etc.
44
45
46.. class:: BaseCookie([input])
47
48 This class is a dictionary-like object whose keys are strings and whose values
49 are :class:`Morsel` instances. Note that upon setting a key to a value, the
50 value is first converted to a :class:`Morsel` containing the key and the value.
51
52 If *input* is given, it is passed to the :meth:`load` method.
53
54
55.. class:: SimpleCookie([input])
56
57 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
58 and :meth:`value_encode` to be the identity and :func:`str` respectively.
59
60
Georg Brandl116aa622007-08-15 14:28:22 +000061.. seealso::
62
Georg Brandl24420152008-05-26 16:32:26 +000063 Module :mod:`http.cookiejar`
64 HTTP cookie handling for web *clients*. The :mod:`http.cookiejar` and
65 :mod:`http.cookies` modules do not depend on each other.
Georg Brandl116aa622007-08-15 14:28:22 +000066
67 :rfc:`2109` - HTTP State Management Mechanism
68 This is the state management specification implemented by this module.
69
70
71.. _cookie-objects:
72
73Cookie Objects
74--------------
75
76
77.. method:: BaseCookie.value_decode(val)
78
79 Return a decoded value from a string representation. Return value can be any
80 type. This method does nothing in :class:`BaseCookie` --- it exists so it can be
81 overridden.
82
83
84.. method:: BaseCookie.value_encode(val)
85
86 Return an encoded value. *val* can be any type, but return value must be a
87 string. This method does nothing in :class:`BaseCookie` --- it exists so it can
Martin Panterd21e0b52015-10-10 10:36:22 +000088 be overridden.
Georg Brandl116aa622007-08-15 14:28:22 +000089
90 In general, it should be the case that :meth:`value_encode` and
91 :meth:`value_decode` are inverses on the range of *value_decode*.
92
93
Georg Brandl036490d2009-05-17 13:00:36 +000094.. method:: BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\\r\\n')
Georg Brandl116aa622007-08-15 14:28:22 +000095
96 Return a string representation suitable to be sent as HTTP headers. *attrs* and
97 *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used
98 to join the headers together, and is by default the combination ``'\r\n'``
99 (CRLF).
100
Georg Brandl116aa622007-08-15 14:28:22 +0000101
Georg Brandl036490d2009-05-17 13:00:36 +0000102.. method:: BaseCookie.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000103
104 Return an embeddable JavaScript snippet, which, if run on a browser which
105 supports JavaScript, will act the same as if the HTTP headers was sent.
106
107 The meaning for *attrs* is the same as in :meth:`output`.
108
109
110.. method:: BaseCookie.load(rawdata)
111
112 If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
113 found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::
114
115 for k, v in rawdata.items():
116 cookie[k] = v
117
118
119.. _morsel-objects:
120
121Morsel Objects
122--------------
123
124
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000125.. class:: Morsel
Georg Brandl116aa622007-08-15 14:28:22 +0000126
127 Abstract a key/value pair, which has some :rfc:`2109` attributes.
128
129 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
130 :rfc:`2109` attributes, which are
131
132 * ``expires``
133 * ``path``
134 * ``comment``
135 * ``domain``
136 * ``max-age``
137 * ``secure``
138 * ``version``
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000139 * ``httponly``
Alex Gaynorc87eb092018-04-07 16:09:42 -0400140 * ``samesite``
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000141
Georg Brandl6faee4e2010-09-21 14:48:28 +0000142 The attribute :attr:`httponly` specifies that the cookie is only transferred
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000143 in HTTP requests, and is not accessible through JavaScript. This is intended
144 to mitigate some forms of cross-site scripting.
Georg Brandl116aa622007-08-15 14:28:22 +0000145
Alex Gaynorc87eb092018-04-07 16:09:42 -0400146 The attribute :attr:`samesite` specifies that the browser is not allowed to
147 send the cookie along with cross-site requests. This helps to mitigate CSRF
148 attacks. Valid values for this attribute are "Strict" and "Lax".
149
Berker Peksag8724a2a2016-04-25 14:32:19 +0300150 The keys are case-insensitive and their default value is ``''``.
Georg Brandl116aa622007-08-15 14:28:22 +0000151
R David Murray1813c172015-03-29 17:09:21 -0400152 .. versionchanged:: 3.5
153 :meth:`~Morsel.__eq__` now takes :attr:`~Morsel.key` and :attr:`~Morsel.value`
154 into account.
155
Serhiy Storchakacc283372017-01-13 09:23:15 +0200156 .. versionchanged:: 3.7
157 Attributes :attr:`~Morsel.key`, :attr:`~Morsel.value` and
158 :attr:`~Morsel.coded_value` are read-only. Use :meth:`~Morsel.set` for
159 setting them.
160
Alex Gaynorc87eb092018-04-07 16:09:42 -0400161 .. versionchanged:: 3.8
162 Added support for the :attr:`samesite` attribute.
163
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165.. attribute:: Morsel.value
166
167 The value of the cookie.
168
169
170.. attribute:: Morsel.coded_value
171
172 The encoded value of the cookie --- this is what should be sent.
173
174
175.. attribute:: Morsel.key
176
177 The name of the cookie.
178
179
180.. method:: Morsel.set(key, value, coded_value)
181
Senthil Kumarana6bac952011-07-04 11:28:30 -0700182 Set the *key*, *value* and *coded_value* attributes.
Georg Brandl116aa622007-08-15 14:28:22 +0000183
184
185.. method:: Morsel.isReservedKey(K)
186
187 Whether *K* is a member of the set of keys of a :class:`Morsel`.
188
189
Georg Brandl036490d2009-05-17 13:00:36 +0000190.. method:: Morsel.output(attrs=None, header='Set-Cookie:')
Georg Brandl116aa622007-08-15 14:28:22 +0000191
192 Return a string representation of the Morsel, suitable to be sent as an HTTP
193 header. By default, all the attributes are included, unless *attrs* is given, in
194 which case it should be a list of attributes to use. *header* is by default
195 ``"Set-Cookie:"``.
196
197
Georg Brandl036490d2009-05-17 13:00:36 +0000198.. method:: Morsel.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000199
200 Return an embeddable JavaScript snippet, which, if run on a browser which
201 supports JavaScript, will act the same as if the HTTP header was sent.
202
203 The meaning for *attrs* is the same as in :meth:`output`.
204
205
Georg Brandl036490d2009-05-17 13:00:36 +0000206.. method:: Morsel.OutputString(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000207
208 Return a string representing the Morsel, without any surrounding HTTP or
209 JavaScript.
210
211 The meaning for *attrs* is the same as in :meth:`output`.
212
213
R David Murray1813c172015-03-29 17:09:21 -0400214.. method:: Morsel.update(values)
215
216 Update the values in the Morsel dictionary with the values in the dictionary
217 *values*. Raise an error if any of the keys in the *values* dict is not a
218 valid :rfc:`2109` attribute.
219
220 .. versionchanged:: 3.5
221 an error is raised for invalid keys.
222
223
224.. method:: Morsel.copy(value)
225
226 Return a shallow copy of the Morsel object.
227
228 .. versionchanged:: 3.5
229 return a Morsel object instead of a dict.
230
231
R David Murrayba6ea9b2015-03-30 11:48:50 -0400232.. method:: Morsel.setdefault(key, value=None)
233
234 Raise an error if key is not a valid :rfc:`2109` attribute, otherwise
235 behave the same as :meth:`dict.setdefault`.
236
237
Georg Brandl116aa622007-08-15 14:28:22 +0000238.. _cookie-example:
239
240Example
241-------
242
Georg Brandl24420152008-05-26 16:32:26 +0000243The following example demonstrates how to use the :mod:`http.cookies` module.
Christian Heimesfe337bf2008-03-23 21:54:12 +0000244
245.. doctest::
246 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000247
Georg Brandl24420152008-05-26 16:32:26 +0000248 >>> from http import cookies
249 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000250 >>> C["fig"] = "newton"
251 >>> C["sugar"] = "wafer"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000252 >>> print(C) # generate HTTP headers
Georg Brandl116aa622007-08-15 14:28:22 +0000253 Set-Cookie: fig=newton
Christian Heimesfe337bf2008-03-23 21:54:12 +0000254 Set-Cookie: sugar=wafer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000255 >>> print(C.output()) # same thing
Georg Brandl116aa622007-08-15 14:28:22 +0000256 Set-Cookie: fig=newton
Christian Heimesfe337bf2008-03-23 21:54:12 +0000257 Set-Cookie: sugar=wafer
Georg Brandl61013952008-05-28 15:56:30 +0000258 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000259 >>> C["rocky"] = "road"
260 >>> C["rocky"]["path"] = "/cookie"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000261 >>> print(C.output(header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000262 Cookie: rocky=road; Path=/cookie
Georg Brandl6911e3c2007-09-04 07:15:32 +0000263 >>> print(C.output(attrs=[], header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000264 Cookie: rocky=road
Georg Brandl61013952008-05-28 15:56:30 +0000265 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000266 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000267 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000268 Set-Cookie: chips=ahoy
Christian Heimesfe337bf2008-03-23 21:54:12 +0000269 Set-Cookie: vienna=finger
Georg Brandl61013952008-05-28 15:56:30 +0000270 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000271 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000272 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000273 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Georg Brandl61013952008-05-28 15:56:30 +0000274 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000275 >>> C["oreo"] = "doublestuff"
276 >>> C["oreo"]["path"] = "/"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000277 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000278 Set-Cookie: oreo=doublestuff; Path=/
Georg Brandl61013952008-05-28 15:56:30 +0000279 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000280 >>> C["twix"] = "none for you"
281 >>> C["twix"].value
282 'none for you'
Georg Brandl24420152008-05-26 16:32:26 +0000283 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000284 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
285 >>> C["string"] = "seven"
286 >>> C["number"].value
287 '7'
288 >>> C["string"].value
289 'seven'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000290 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000291 Set-Cookie: number=7
292 Set-Cookie: string=seven