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