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