blob: 346da5a1fd921eb8a5155db41f5b3dffeaf331ca [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
151.. class:: Morsel()
152
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``
165
166 The keys are case-insensitive.
167
168
169.. attribute:: Morsel.value
170
171 The value of the cookie.
172
173
174.. attribute:: Morsel.coded_value
175
176 The encoded value of the cookie --- this is what should be sent.
177
178
179.. attribute:: Morsel.key
180
181 The name of the cookie.
182
183
184.. method:: Morsel.set(key, value, coded_value)
185
186 Set the *key*, *value* and *coded_value* members.
187
188
189.. method:: Morsel.isReservedKey(K)
190
191 Whether *K* is a member of the set of keys of a :class:`Morsel`.
192
193
194.. method:: Morsel.output([attrs[, header]])
195
196 Return a string representation of the Morsel, suitable to be sent as an HTTP
197 header. By default, all the attributes are included, unless *attrs* is given, in
198 which case it should be a list of attributes to use. *header* is by default
199 ``"Set-Cookie:"``.
200
201
202.. method:: Morsel.js_output([attrs])
203
204 Return an embeddable JavaScript snippet, which, if run on a browser which
205 supports JavaScript, will act the same as if the HTTP header was sent.
206
207 The meaning for *attrs* is the same as in :meth:`output`.
208
209
210.. method:: Morsel.OutputString([attrs])
211
212 Return a string representing the Morsel, without any surrounding HTTP or
213 JavaScript.
214
215 The meaning for *attrs* is the same as in :meth:`output`.
216
217
218.. _cookie-example:
219
220Example
221-------
222
Georg Brandle8f1b002008-03-22 22:04:10 +0000223The following example demonstrates how to use the :mod:`Cookie` module.
224
225.. doctest::
226 :options: +NORMALIZE_WHITESPACE
Georg Brandl8ec7f652007-08-15 14:28:01 +0000227
228 >>> import Cookie
229 >>> C = Cookie.SimpleCookie()
230 >>> C = Cookie.SerialCookie()
231 >>> C = Cookie.SmartCookie()
232 >>> C["fig"] = "newton"
233 >>> C["sugar"] = "wafer"
234 >>> print C # generate HTTP headers
Georg Brandl8ec7f652007-08-15 14:28:01 +0000235 Set-Cookie: fig=newton
Georg Brandle8f1b002008-03-22 22:04:10 +0000236 Set-Cookie: sugar=wafer
Georg Brandl8ec7f652007-08-15 14:28:01 +0000237 >>> print C.output() # same thing
Georg Brandl8ec7f652007-08-15 14:28:01 +0000238 Set-Cookie: fig=newton
Georg Brandle8f1b002008-03-22 22:04:10 +0000239 Set-Cookie: sugar=wafer
Georg Brandl8ec7f652007-08-15 14:28:01 +0000240 >>> C = Cookie.SmartCookie()
241 >>> C["rocky"] = "road"
242 >>> C["rocky"]["path"] = "/cookie"
243 >>> print C.output(header="Cookie:")
244 Cookie: rocky=road; Path=/cookie
245 >>> print C.output(attrs=[], header="Cookie:")
246 Cookie: rocky=road
247 >>> C = Cookie.SmartCookie()
248 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
249 >>> print C
Georg Brandl8ec7f652007-08-15 14:28:01 +0000250 Set-Cookie: chips=ahoy
Georg Brandle8f1b002008-03-22 22:04:10 +0000251 Set-Cookie: vienna=finger
Georg Brandl8ec7f652007-08-15 14:28:01 +0000252 >>> C = Cookie.SmartCookie()
253 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
254 >>> print C
255 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
256 >>> C = Cookie.SmartCookie()
257 >>> C["oreo"] = "doublestuff"
258 >>> C["oreo"]["path"] = "/"
259 >>> print C
260 Set-Cookie: oreo=doublestuff; Path=/
261 >>> C = Cookie.SmartCookie()
262 >>> C["twix"] = "none for you"
263 >>> C["twix"].value
264 'none for you'
265 >>> C = Cookie.SimpleCookie()
266 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
267 >>> C["string"] = "seven"
268 >>> C["number"].value
269 '7'
270 >>> C["string"].value
271 'seven'
272 >>> print C
273 Set-Cookie: number=7
274 Set-Cookie: string=seven
275 >>> C = Cookie.SerialCookie()
276 >>> C["number"] = 7
277 >>> C["string"] = "seven"
278 >>> C["number"].value
279 7
280 >>> C["string"].value
281 'seven'
282 >>> print C
283 Set-Cookie: number="I7\012."
284 Set-Cookie: string="S'seven'\012p1\012."
285 >>> C = Cookie.SmartCookie()
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=seven
295