blob: 19786f7da22ba18ef1929d13d2b691afd6fa7f6b [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001:mod:`Cookie` --- HTTP state management
2=======================================
3
4.. module:: Cookie
5 :synopsis: Support for HTTP state management (cookies).
6.. moduleauthor:: Timothy O'Malley <timo@alum.mit.edu>
7.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
8
Georg Brandl8de91192008-05-26 15:01:48 +00009.. note::
10 The :mod:`Cookie` module has been renamed to :mod:`http.cookies` in Python
Ezio Melotti510ff542012-05-03 19:21:40 +030011 3. The :term:`2to3` tool will automatically adapt imports when converting
12 your sources to Python 3.
Georg Brandl8de91192008-05-26 15:01:48 +000013
Éric Araujo29a0b572011-08-19 02:14:03 +020014**Source code:** :source:`Lib/Cookie.py`
15
16--------------
Georg Brandl8ec7f652007-08-15 14:28:01 +000017
18The :mod:`Cookie` module defines classes for abstracting the concept of
19cookies, an HTTP state management mechanism. It supports both simple string-only
20cookies, and provides an abstraction for having any serializable data-type as
21cookie value.
22
23The module formerly strictly applied the parsing rules described in the
24:rfc:`2109` and :rfc:`2068` specifications. It has since been discovered that
Senthil Kumaranea170822012-04-22 10:27:22 +080025MSIE 3.0x doesn't follow the character rules outlined in those specs and also
26many current day browsers and servers have relaxed parsing rules when comes to
27Cookie handling. As a result, the parsing rules used are a bit less strict.
28
29The character set, :data:`string.ascii_letters`, :data:`string.digits` and
30``!#$%&'*+-.^_`|~`` denote the set of valid characters allowed by this module
31in Cookie name (as :attr:`~Morsel.key`).
32
Georg Brandl8ec7f652007-08-15 14:28:01 +000033
Georg Brandlb77e8882008-05-29 07:38:37 +000034.. 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
Georg Brandl8ec7f652007-08-15 14:28:01 +000040
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:`value_decode`
59 and :meth:`value_encode` to be the identity and :func:`str` respectively.
60
61
62.. class:: SerialCookie([input])
63
64 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
65 and :meth:`value_encode` to be the :func:`pickle.loads` and
66 :func:`pickle.dumps`.
67
68 .. deprecated:: 2.3
69 Reading pickled values from untrusted cookie data is a huge security hole, as
70 pickle strings can be crafted to cause arbitrary code to execute on your server.
71 It is supported for backwards compatibility only, and may eventually go away.
72
73
74.. class:: SmartCookie([input])
75
76 This class derives from :class:`BaseCookie`. It overrides :meth:`value_decode`
77 to be :func:`pickle.loads` if it is a valid pickle, and otherwise the value
78 itself. It overrides :meth:`value_encode` to be :func:`pickle.dumps` unless it
79 is a string, in which case it returns the value itself.
80
81 .. deprecated:: 2.3
82 The same security warning from :class:`SerialCookie` applies here.
83
84A further security note is warranted. For backwards compatibility, the
85:mod:`Cookie` module exports a class named :class:`Cookie` which is just an
86alias for :class:`SmartCookie`. This is probably a mistake and will likely be
87removed in a future version. You should not use the :class:`Cookie` class in
88your applications, for the same reason why you should not use the
89:class:`SerialCookie` class.
90
91
92.. seealso::
93
94 Module :mod:`cookielib`
95 HTTP cookie handling for web *clients*. The :mod:`cookielib` and :mod:`Cookie`
96 modules do not depend on each other.
97
98 :rfc:`2109` - HTTP State Management Mechanism
99 This is the state management specification implemented by this module.
100
101
102.. _cookie-objects:
103
104Cookie Objects
105--------------
106
107
108.. method:: BaseCookie.value_decode(val)
109
110 Return a decoded value from a string representation. Return value can be any
111 type. This method does nothing in :class:`BaseCookie` --- it exists so it can be
112 overridden.
113
114
115.. method:: BaseCookie.value_encode(val)
116
117 Return an encoded value. *val* can be any type, but return value must be a
118 string. This method does nothing in :class:`BaseCookie` --- it exists so it can
119 be overridden
120
121 In general, it should be the case that :meth:`value_encode` and
122 :meth:`value_decode` are inverses on the range of *value_decode*.
123
124
125.. method:: BaseCookie.output([attrs[, header[, sep]]])
126
127 Return a string representation suitable to be sent as HTTP headers. *attrs* and
128 *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used
129 to join the headers together, and is by default the combination ``'\r\n'``
130 (CRLF).
131
132 .. versionchanged:: 2.5
133 The default separator has been changed from ``'\n'`` to match the cookie
134 specification.
135
136
137.. method:: BaseCookie.js_output([attrs])
138
139 Return an embeddable JavaScript snippet, which, if run on a browser which
140 supports JavaScript, will act the same as if the HTTP headers was sent.
141
142 The meaning for *attrs* is the same as in :meth:`output`.
143
144
145.. method:: BaseCookie.load(rawdata)
146
147 If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
148 found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::
149
150 for k, v in rawdata.items():
151 cookie[k] = v
152
153
154.. _morsel-objects:
155
156Morsel Objects
157--------------
158
159
Benjamin Peterson6ac7d7c2008-09-06 19:28:11 +0000160.. class:: Morsel
Georg Brandl8ec7f652007-08-15 14:28:01 +0000161
162 Abstract a key/value pair, which has some :rfc:`2109` attributes.
163
164 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
165 :rfc:`2109` attributes, which are
166
167 * ``expires``
168 * ``path``
169 * ``comment``
170 * ``domain``
171 * ``max-age``
172 * ``secure``
173 * ``version``
Benjamin Peterson6ac7d7c2008-09-06 19:28:11 +0000174 * ``httponly``
175
176 The attribute :attr:`httponly` specifies that the cookie is only transfered
177 in HTTP requests, and is not accessible through JavaScript. This is intended
178 to mitigate some forms of cross-site scripting.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179
180 The keys are case-insensitive.
181
Benjamin Peterson6ac7d7c2008-09-06 19:28:11 +0000182 .. versionadded:: 2.6
183 The :attr:`httponly` attribute was added.
184
Georg Brandl8ec7f652007-08-15 14:28:01 +0000185
186.. attribute:: Morsel.value
187
188 The value of the cookie.
189
190
191.. attribute:: Morsel.coded_value
192
193 The encoded value of the cookie --- this is what should be sent.
194
195
196.. attribute:: Morsel.key
197
198 The name of the cookie.
199
200
201.. method:: Morsel.set(key, value, coded_value)
202
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700203 Set the *key*, *value* and *coded_value* attributes.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000204
205
206.. method:: Morsel.isReservedKey(K)
207
208 Whether *K* is a member of the set of keys of a :class:`Morsel`.
209
210
211.. method:: Morsel.output([attrs[, header]])
212
213 Return a string representation of the Morsel, suitable to be sent as an HTTP
214 header. By default, all the attributes are included, unless *attrs* is given, in
215 which case it should be a list of attributes to use. *header* is by default
216 ``"Set-Cookie:"``.
217
218
219.. method:: Morsel.js_output([attrs])
220
221 Return an embeddable JavaScript snippet, which, if run on a browser which
222 supports JavaScript, will act the same as if the HTTP header was sent.
223
224 The meaning for *attrs* is the same as in :meth:`output`.
225
226
227.. method:: Morsel.OutputString([attrs])
228
229 Return a string representing the Morsel, without any surrounding HTTP or
230 JavaScript.
231
232 The meaning for *attrs* is the same as in :meth:`output`.
233
234
235.. _cookie-example:
236
237Example
238-------
239
Georg Brandle8f1b002008-03-22 22:04:10 +0000240The following example demonstrates how to use the :mod:`Cookie` module.
241
242.. doctest::
243 :options: +NORMALIZE_WHITESPACE
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244
245 >>> import Cookie
246 >>> C = Cookie.SimpleCookie()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000247 >>> C["fig"] = "newton"
248 >>> C["sugar"] = "wafer"
249 >>> print C # generate HTTP headers
Georg Brandl8ec7f652007-08-15 14:28:01 +0000250 Set-Cookie: fig=newton
Georg Brandle8f1b002008-03-22 22:04:10 +0000251 Set-Cookie: sugar=wafer
Georg Brandl8ec7f652007-08-15 14:28:01 +0000252 >>> print C.output() # same thing
Georg Brandl8ec7f652007-08-15 14:28:01 +0000253 Set-Cookie: fig=newton
Georg Brandle8f1b002008-03-22 22:04:10 +0000254 Set-Cookie: sugar=wafer
Senthil Kumaran4b517db2010-09-22 05:45:14 +0000255 >>> C = Cookie.SimpleCookie()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000256 >>> C["rocky"] = "road"
257 >>> C["rocky"]["path"] = "/cookie"
258 >>> print C.output(header="Cookie:")
259 Cookie: rocky=road; Path=/cookie
260 >>> print C.output(attrs=[], header="Cookie:")
261 Cookie: rocky=road
Senthil Kumaran4b517db2010-09-22 05:45:14 +0000262 >>> C = Cookie.SimpleCookie()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000263 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
264 >>> print C
Georg Brandl8ec7f652007-08-15 14:28:01 +0000265 Set-Cookie: chips=ahoy
Georg Brandle8f1b002008-03-22 22:04:10 +0000266 Set-Cookie: vienna=finger
Senthil Kumaran4b517db2010-09-22 05:45:14 +0000267 >>> C = Cookie.SimpleCookie()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000268 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
269 >>> print C
270 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Senthil Kumaran4b517db2010-09-22 05:45:14 +0000271 >>> C = Cookie.SimpleCookie()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000272 >>> C["oreo"] = "doublestuff"
273 >>> C["oreo"]["path"] = "/"
274 >>> print C
275 Set-Cookie: oreo=doublestuff; Path=/
Georg Brandl8ec7f652007-08-15 14:28:01 +0000276 >>> C["twix"] = "none for you"
277 >>> C["twix"].value
278 'none for you'
279 >>> C = Cookie.SimpleCookie()
280 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
281 >>> C["string"] = "seven"
282 >>> C["number"].value
283 '7'
284 >>> C["string"].value
285 'seven'
286 >>> print C
287 Set-Cookie: number=7
288 Set-Cookie: string=seven
Senthil Kumaran4b517db2010-09-22 05:45:14 +0000289 >>> # SerialCookie and SmartCookie are deprecated
290 >>> # using it can cause security loopholes in your code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000291 >>> C = Cookie.SerialCookie()
292 >>> C["number"] = 7
293 >>> C["string"] = "seven"
294 >>> C["number"].value
295 7
296 >>> C["string"].value
297 'seven'
298 >>> print C
299 Set-Cookie: number="I7\012."
300 Set-Cookie: string="S'seven'\012p1\012."
301 >>> C = Cookie.SmartCookie()
302 >>> C["number"] = 7
303 >>> C["string"] = "seven"
304 >>> C["number"].value
305 7
306 >>> C["string"].value
307 'seven'
308 >>> print C
309 Set-Cookie: number="I7\012."
310 Set-Cookie: string=seven
311