blob: 480dffa66e620c519048d76327935ef371db29ef [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
11 3.0. The :term:`2to3` tool will automatically adapt imports when converting
12 your sources to 3.0.
13
É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
25MSIE 3.0x doesn't follow the character rules outlined in those specs. As a
26result, the parsing rules used are a bit less strict.
27
Georg Brandlb77e8882008-05-29 07:38:37 +000028.. note::
29
30 On encountering an invalid cookie, :exc:`CookieError` is raised, so if your
31 cookie data comes from a browser you should always prepare for invalid data
32 and catch :exc:`CookieError` on parsing.
33
Georg Brandl8ec7f652007-08-15 14:28:01 +000034
35.. exception:: CookieError
36
37 Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
38 incorrect :mailheader:`Set-Cookie` header, etc.
39
40
41.. class:: BaseCookie([input])
42
43 This class is a dictionary-like object whose keys are strings and whose values
44 are :class:`Morsel` instances. Note that upon setting a key to a value, the
45 value is first converted to a :class:`Morsel` containing the key and the value.
46
47 If *input* is given, it is passed to the :meth:`load` method.
48
49
50.. class:: SimpleCookie([input])
51
52 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
53 and :meth:`value_encode` to be the identity and :func:`str` respectively.
54
55
56.. class:: SerialCookie([input])
57
58 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
59 and :meth:`value_encode` to be the :func:`pickle.loads` and
60 :func:`pickle.dumps`.
61
62 .. deprecated:: 2.3
63 Reading pickled values from untrusted cookie data is a huge security hole, as
64 pickle strings can be crafted to cause arbitrary code to execute on your server.
65 It is supported for backwards compatibility only, and may eventually go away.
66
67
68.. class:: SmartCookie([input])
69
70 This class derives from :class:`BaseCookie`. It overrides :meth:`value_decode`
71 to be :func:`pickle.loads` if it is a valid pickle, and otherwise the value
72 itself. It overrides :meth:`value_encode` to be :func:`pickle.dumps` unless it
73 is a string, in which case it returns the value itself.
74
75 .. deprecated:: 2.3
76 The same security warning from :class:`SerialCookie` applies here.
77
78A further security note is warranted. For backwards compatibility, the
79:mod:`Cookie` module exports a class named :class:`Cookie` which is just an
80alias for :class:`SmartCookie`. This is probably a mistake and will likely be
81removed in a future version. You should not use the :class:`Cookie` class in
82your applications, for the same reason why you should not use the
83:class:`SerialCookie` class.
84
85
86.. seealso::
87
88 Module :mod:`cookielib`
89 HTTP cookie handling for web *clients*. The :mod:`cookielib` and :mod:`Cookie`
90 modules do not depend on each other.
91
92 :rfc:`2109` - HTTP State Management Mechanism
93 This is the state management specification implemented by this module.
94
95
96.. _cookie-objects:
97
98Cookie Objects
99--------------
100
101
102.. method:: BaseCookie.value_decode(val)
103
104 Return a decoded value from a string representation. Return value can be any
105 type. This method does nothing in :class:`BaseCookie` --- it exists so it can be
106 overridden.
107
108
109.. method:: BaseCookie.value_encode(val)
110
111 Return an encoded value. *val* can be any type, but return value must be a
112 string. This method does nothing in :class:`BaseCookie` --- it exists so it can
113 be overridden
114
115 In general, it should be the case that :meth:`value_encode` and
116 :meth:`value_decode` are inverses on the range of *value_decode*.
117
118
119.. method:: BaseCookie.output([attrs[, header[, sep]]])
120
121 Return a string representation suitable to be sent as HTTP headers. *attrs* and
122 *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used
123 to join the headers together, and is by default the combination ``'\r\n'``
124 (CRLF).
125
126 .. versionchanged:: 2.5
127 The default separator has been changed from ``'\n'`` to match the cookie
128 specification.
129
130
131.. method:: BaseCookie.js_output([attrs])
132
133 Return an embeddable JavaScript snippet, which, if run on a browser which
134 supports JavaScript, will act the same as if the HTTP headers was sent.
135
136 The meaning for *attrs* is the same as in :meth:`output`.
137
138
139.. method:: BaseCookie.load(rawdata)
140
141 If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
142 found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::
143
144 for k, v in rawdata.items():
145 cookie[k] = v
146
147
148.. _morsel-objects:
149
150Morsel Objects
151--------------
152
153
Benjamin Peterson6ac7d7c2008-09-06 19:28:11 +0000154.. class:: Morsel
Georg Brandl8ec7f652007-08-15 14:28:01 +0000155
156 Abstract a key/value pair, which has some :rfc:`2109` attributes.
157
158 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
159 :rfc:`2109` attributes, which are
160
161 * ``expires``
162 * ``path``
163 * ``comment``
164 * ``domain``
165 * ``max-age``
166 * ``secure``
167 * ``version``
Benjamin Peterson6ac7d7c2008-09-06 19:28:11 +0000168 * ``httponly``
169
170 The attribute :attr:`httponly` specifies that the cookie is only transfered
171 in HTTP requests, and is not accessible through JavaScript. This is intended
172 to mitigate some forms of cross-site scripting.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000173
174 The keys are case-insensitive.
175
Benjamin Peterson6ac7d7c2008-09-06 19:28:11 +0000176 .. versionadded:: 2.6
177 The :attr:`httponly` attribute was added.
178
Georg Brandl8ec7f652007-08-15 14:28:01 +0000179
180.. attribute:: Morsel.value
181
182 The value of the cookie.
183
184
185.. attribute:: Morsel.coded_value
186
187 The encoded value of the cookie --- this is what should be sent.
188
189
190.. attribute:: Morsel.key
191
192 The name of the cookie.
193
194
195.. method:: Morsel.set(key, value, coded_value)
196
Senthil Kumaran6f18b982011-07-04 12:50:02 -0700197 Set the *key*, *value* and *coded_value* attributes.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000198
199
200.. method:: Morsel.isReservedKey(K)
201
202 Whether *K* is a member of the set of keys of a :class:`Morsel`.
203
204
205.. method:: Morsel.output([attrs[, header]])
206
207 Return a string representation of the Morsel, suitable to be sent as an HTTP
208 header. By default, all the attributes are included, unless *attrs* is given, in
209 which case it should be a list of attributes to use. *header* is by default
210 ``"Set-Cookie:"``.
211
212
213.. method:: Morsel.js_output([attrs])
214
215 Return an embeddable JavaScript snippet, which, if run on a browser which
216 supports JavaScript, will act the same as if the HTTP header was sent.
217
218 The meaning for *attrs* is the same as in :meth:`output`.
219
220
221.. method:: Morsel.OutputString([attrs])
222
223 Return a string representing the Morsel, without any surrounding HTTP or
224 JavaScript.
225
226 The meaning for *attrs* is the same as in :meth:`output`.
227
228
229.. _cookie-example:
230
231Example
232-------
233
Georg Brandle8f1b002008-03-22 22:04:10 +0000234The following example demonstrates how to use the :mod:`Cookie` module.
235
236.. doctest::
237 :options: +NORMALIZE_WHITESPACE
Georg Brandl8ec7f652007-08-15 14:28:01 +0000238
239 >>> import Cookie
240 >>> C = Cookie.SimpleCookie()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000241 >>> C["fig"] = "newton"
242 >>> C["sugar"] = "wafer"
243 >>> print C # generate HTTP headers
Georg Brandl8ec7f652007-08-15 14:28:01 +0000244 Set-Cookie: fig=newton
Georg Brandle8f1b002008-03-22 22:04:10 +0000245 Set-Cookie: sugar=wafer
Georg Brandl8ec7f652007-08-15 14:28:01 +0000246 >>> print C.output() # same thing
Georg Brandl8ec7f652007-08-15 14:28:01 +0000247 Set-Cookie: fig=newton
Georg Brandle8f1b002008-03-22 22:04:10 +0000248 Set-Cookie: sugar=wafer
Senthil Kumaran4b517db2010-09-22 05:45:14 +0000249 >>> C = Cookie.SimpleCookie()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000250 >>> C["rocky"] = "road"
251 >>> C["rocky"]["path"] = "/cookie"
252 >>> print C.output(header="Cookie:")
253 Cookie: rocky=road; Path=/cookie
254 >>> print C.output(attrs=[], header="Cookie:")
255 Cookie: rocky=road
Senthil Kumaran4b517db2010-09-22 05:45:14 +0000256 >>> C = Cookie.SimpleCookie()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000257 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
258 >>> print C
Georg Brandl8ec7f652007-08-15 14:28:01 +0000259 Set-Cookie: chips=ahoy
Georg Brandle8f1b002008-03-22 22:04:10 +0000260 Set-Cookie: vienna=finger
Senthil Kumaran4b517db2010-09-22 05:45:14 +0000261 >>> C = Cookie.SimpleCookie()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000262 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
263 >>> print C
264 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Senthil Kumaran4b517db2010-09-22 05:45:14 +0000265 >>> C = Cookie.SimpleCookie()
Georg Brandl8ec7f652007-08-15 14:28:01 +0000266 >>> C["oreo"] = "doublestuff"
267 >>> C["oreo"]["path"] = "/"
268 >>> print C
269 Set-Cookie: oreo=doublestuff; Path=/
Georg Brandl8ec7f652007-08-15 14:28:01 +0000270 >>> C["twix"] = "none for you"
271 >>> C["twix"].value
272 'none for you'
273 >>> C = Cookie.SimpleCookie()
274 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
275 >>> C["string"] = "seven"
276 >>> C["number"].value
277 '7'
278 >>> C["string"].value
279 'seven'
280 >>> print C
281 Set-Cookie: number=7
282 Set-Cookie: string=seven
Senthil Kumaran4b517db2010-09-22 05:45:14 +0000283 >>> # SerialCookie and SmartCookie are deprecated
284 >>> # using it can cause security loopholes in your code.
Georg Brandl8ec7f652007-08-15 14:28:01 +0000285 >>> C = Cookie.SerialCookie()
286 >>> C["number"] = 7
287 >>> C["string"] = "seven"
288 >>> C["number"].value
289 7
290 >>> C["string"].value
291 'seven'
292 >>> print C
293 Set-Cookie: number="I7\012."
294 Set-Cookie: string="S'seven'\012p1\012."
295 >>> C = Cookie.SmartCookie()
296 >>> C["number"] = 7
297 >>> C["string"] = "seven"
298 >>> C["number"].value
299 7
300 >>> C["string"].value
301 'seven'
302 >>> print C
303 Set-Cookie: number="I7\012."
304 Set-Cookie: string=seven
305