blob: 5a5808f1ecb42d3425afcd1f8e0631594002a144 [file] [log] [blame]
Georg Brandl8ec7f652007-08-15 14:28:01 +00001
2:mod:`Cookie` --- HTTP state management
3=======================================
4
5.. module:: Cookie
6 :synopsis: Support for HTTP state management (cookies).
7.. moduleauthor:: Timothy O'Malley <timo@alum.mit.edu>
8.. sectionauthor:: Moshe Zadka <moshez@zadka.site.co.il>
9
10
11The :mod:`Cookie` module defines classes for abstracting the concept of
12cookies, an HTTP state management mechanism. It supports both simple string-only
13cookies, and provides an abstraction for having any serializable data-type as
14cookie value.
15
16The module formerly strictly applied the parsing rules described in the
17:rfc:`2109` and :rfc:`2068` specifications. It has since been discovered that
18MSIE 3.0x doesn't follow the character rules outlined in those specs. As a
19result, the parsing rules used are a bit less strict.
20
21
22.. exception:: CookieError
23
24 Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
25 incorrect :mailheader:`Set-Cookie` header, etc.
26
27
28.. class:: BaseCookie([input])
29
30 This class is a dictionary-like object whose keys are strings and whose values
31 are :class:`Morsel` instances. Note that upon setting a key to a value, the
32 value is first converted to a :class:`Morsel` containing the key and the value.
33
34 If *input* is given, it is passed to the :meth:`load` method.
35
36
37.. class:: SimpleCookie([input])
38
39 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
40 and :meth:`value_encode` to be the identity and :func:`str` respectively.
41
42
43.. class:: SerialCookie([input])
44
45 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
46 and :meth:`value_encode` to be the :func:`pickle.loads` and
47 :func:`pickle.dumps`.
48
49 .. deprecated:: 2.3
50 Reading pickled values from untrusted cookie data is a huge security hole, as
51 pickle strings can be crafted to cause arbitrary code to execute on your server.
52 It is supported for backwards compatibility only, and may eventually go away.
53
54
55.. class:: SmartCookie([input])
56
57 This class derives from :class:`BaseCookie`. It overrides :meth:`value_decode`
58 to be :func:`pickle.loads` if it is a valid pickle, and otherwise the value
59 itself. It overrides :meth:`value_encode` to be :func:`pickle.dumps` unless it
60 is a string, in which case it returns the value itself.
61
62 .. deprecated:: 2.3
63 The same security warning from :class:`SerialCookie` applies here.
64
65A further security note is warranted. For backwards compatibility, the
66:mod:`Cookie` module exports a class named :class:`Cookie` which is just an
67alias for :class:`SmartCookie`. This is probably a mistake and will likely be
68removed in a future version. You should not use the :class:`Cookie` class in
69your applications, for the same reason why you should not use the
70:class:`SerialCookie` class.
71
72
73.. seealso::
74
75 Module :mod:`cookielib`
76 HTTP cookie handling for web *clients*. The :mod:`cookielib` and :mod:`Cookie`
77 modules do not depend on each other.
78
79 :rfc:`2109` - HTTP State Management Mechanism
80 This is the state management specification implemented by this module.
81
82
83.. _cookie-objects:
84
85Cookie Objects
86--------------
87
88
89.. method:: BaseCookie.value_decode(val)
90
91 Return a decoded value from a string representation. Return value can be any
92 type. This method does nothing in :class:`BaseCookie` --- it exists so it can be
93 overridden.
94
95
96.. method:: BaseCookie.value_encode(val)
97
98 Return an encoded value. *val* can be any type, but return value must be a
99 string. This method does nothing in :class:`BaseCookie` --- it exists so it can
100 be overridden
101
102 In general, it should be the case that :meth:`value_encode` and
103 :meth:`value_decode` are inverses on the range of *value_decode*.
104
105
106.. method:: BaseCookie.output([attrs[, header[, sep]]])
107
108 Return a string representation suitable to be sent as HTTP headers. *attrs* and
109 *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used
110 to join the headers together, and is by default the combination ``'\r\n'``
111 (CRLF).
112
113 .. versionchanged:: 2.5
114 The default separator has been changed from ``'\n'`` to match the cookie
115 specification.
116
117
118.. method:: BaseCookie.js_output([attrs])
119
120 Return an embeddable JavaScript snippet, which, if run on a browser which
121 supports JavaScript, will act the same as if the HTTP headers was sent.
122
123 The meaning for *attrs* is the same as in :meth:`output`.
124
125
126.. method:: BaseCookie.load(rawdata)
127
128 If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
129 found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::
130
131 for k, v in rawdata.items():
132 cookie[k] = v
133
134
135.. _morsel-objects:
136
137Morsel Objects
138--------------
139
140
141.. class:: Morsel()
142
143 Abstract a key/value pair, which has some :rfc:`2109` attributes.
144
145 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
146 :rfc:`2109` attributes, which are
147
148 * ``expires``
149 * ``path``
150 * ``comment``
151 * ``domain``
152 * ``max-age``
153 * ``secure``
154 * ``version``
155
156 The keys are case-insensitive.
157
158
159.. attribute:: Morsel.value
160
161 The value of the cookie.
162
163
164.. attribute:: Morsel.coded_value
165
166 The encoded value of the cookie --- this is what should be sent.
167
168
169.. attribute:: Morsel.key
170
171 The name of the cookie.
172
173
174.. method:: Morsel.set(key, value, coded_value)
175
176 Set the *key*, *value* and *coded_value* members.
177
178
179.. method:: Morsel.isReservedKey(K)
180
181 Whether *K* is a member of the set of keys of a :class:`Morsel`.
182
183
184.. method:: Morsel.output([attrs[, header]])
185
186 Return a string representation of the Morsel, suitable to be sent as an HTTP
187 header. By default, all the attributes are included, unless *attrs* is given, in
188 which case it should be a list of attributes to use. *header* is by default
189 ``"Set-Cookie:"``.
190
191
192.. method:: Morsel.js_output([attrs])
193
194 Return an embeddable JavaScript snippet, which, if run on a browser which
195 supports JavaScript, will act the same as if the HTTP header was sent.
196
197 The meaning for *attrs* is the same as in :meth:`output`.
198
199
200.. method:: Morsel.OutputString([attrs])
201
202 Return a string representing the Morsel, without any surrounding HTTP or
203 JavaScript.
204
205 The meaning for *attrs* is the same as in :meth:`output`.
206
207
208.. _cookie-example:
209
210Example
211-------
212
213The following example demonstrates how to use the :mod:`Cookie` module. ::
214
215 >>> import Cookie
216 >>> C = Cookie.SimpleCookie()
217 >>> C = Cookie.SerialCookie()
218 >>> C = Cookie.SmartCookie()
219 >>> C["fig"] = "newton"
220 >>> C["sugar"] = "wafer"
221 >>> print C # generate HTTP headers
222 Set-Cookie: sugar=wafer
223 Set-Cookie: fig=newton
224 >>> print C.output() # same thing
225 Set-Cookie: sugar=wafer
226 Set-Cookie: fig=newton
227 >>> C = Cookie.SmartCookie()
228 >>> C["rocky"] = "road"
229 >>> C["rocky"]["path"] = "/cookie"
230 >>> print C.output(header="Cookie:")
231 Cookie: rocky=road; Path=/cookie
232 >>> print C.output(attrs=[], header="Cookie:")
233 Cookie: rocky=road
234 >>> C = Cookie.SmartCookie()
235 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
236 >>> print C
237 Set-Cookie: vienna=finger
238 Set-Cookie: chips=ahoy
239 >>> C = Cookie.SmartCookie()
240 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
241 >>> print C
242 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
243 >>> C = Cookie.SmartCookie()
244 >>> C["oreo"] = "doublestuff"
245 >>> C["oreo"]["path"] = "/"
246 >>> print C
247 Set-Cookie: oreo=doublestuff; Path=/
248 >>> C = Cookie.SmartCookie()
249 >>> C["twix"] = "none for you"
250 >>> C["twix"].value
251 'none for you'
252 >>> C = Cookie.SimpleCookie()
253 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
254 >>> C["string"] = "seven"
255 >>> C["number"].value
256 '7'
257 >>> C["string"].value
258 'seven'
259 >>> print C
260 Set-Cookie: number=7
261 Set-Cookie: string=seven
262 >>> C = Cookie.SerialCookie()
263 >>> C["number"] = 7
264 >>> C["string"] = "seven"
265 >>> C["number"].value
266 7
267 >>> C["string"].value
268 'seven'
269 >>> print C
270 Set-Cookie: number="I7\012."
271 Set-Cookie: string="S'seven'\012p1\012."
272 >>> C = Cookie.SmartCookie()
273 >>> C["number"] = 7
274 >>> C["string"] = "seven"
275 >>> C["number"].value
276 7
277 >>> C["string"].value
278 'seven'
279 >>> print C
280 Set-Cookie: number="I7\012."
281 Set-Cookie: string=seven
282