blob: 84ac72a8bba2adfeb3b5f5cecee7fdb0206e0028 [file] [log] [blame]
Georg Brandl116aa622007-08-15 14:28:22 +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
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114.. method:: BaseCookie.js_output([attrs])
115
116 Return an embeddable JavaScript snippet, which, if run on a browser which
117 supports JavaScript, will act the same as if the HTTP headers was sent.
118
119 The meaning for *attrs* is the same as in :meth:`output`.
120
121
122.. method:: BaseCookie.load(rawdata)
123
124 If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
125 found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::
126
127 for k, v in rawdata.items():
128 cookie[k] = v
129
130
131.. _morsel-objects:
132
133Morsel Objects
134--------------
135
136
137.. class:: Morsel()
138
139 Abstract a key/value pair, which has some :rfc:`2109` attributes.
140
141 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
142 :rfc:`2109` attributes, which are
143
144 * ``expires``
145 * ``path``
146 * ``comment``
147 * ``domain``
148 * ``max-age``
149 * ``secure``
150 * ``version``
151
152 The keys are case-insensitive.
153
154
155.. attribute:: Morsel.value
156
157 The value of the cookie.
158
159
160.. attribute:: Morsel.coded_value
161
162 The encoded value of the cookie --- this is what should be sent.
163
164
165.. attribute:: Morsel.key
166
167 The name of the cookie.
168
169
170.. method:: Morsel.set(key, value, coded_value)
171
172 Set the *key*, *value* and *coded_value* members.
173
174
175.. method:: Morsel.isReservedKey(K)
176
177 Whether *K* is a member of the set of keys of a :class:`Morsel`.
178
179
180.. method:: Morsel.output([attrs[, header]])
181
182 Return a string representation of the Morsel, suitable to be sent as an HTTP
183 header. By default, all the attributes are included, unless *attrs* is given, in
184 which case it should be a list of attributes to use. *header* is by default
185 ``"Set-Cookie:"``.
186
187
188.. method:: Morsel.js_output([attrs])
189
190 Return an embeddable JavaScript snippet, which, if run on a browser which
191 supports JavaScript, will act the same as if the HTTP header was sent.
192
193 The meaning for *attrs* is the same as in :meth:`output`.
194
195
196.. method:: Morsel.OutputString([attrs])
197
198 Return a string representing the Morsel, without any surrounding HTTP or
199 JavaScript.
200
201 The meaning for *attrs* is the same as in :meth:`output`.
202
203
204.. _cookie-example:
205
206Example
207-------
208
209The following example demonstrates how to use the :mod:`Cookie` module. ::
210
211 >>> import Cookie
212 >>> C = Cookie.SimpleCookie()
213 >>> C = Cookie.SerialCookie()
214 >>> C = Cookie.SmartCookie()
215 >>> C["fig"] = "newton"
216 >>> C["sugar"] = "wafer"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000217 >>> print(C) # generate HTTP headers
Georg Brandl116aa622007-08-15 14:28:22 +0000218 Set-Cookie: sugar=wafer
219 Set-Cookie: fig=newton
Georg Brandl6911e3c2007-09-04 07:15:32 +0000220 >>> print(C.output()) # same thing
Georg Brandl116aa622007-08-15 14:28:22 +0000221 Set-Cookie: sugar=wafer
222 Set-Cookie: fig=newton
223 >>> C = Cookie.SmartCookie()
224 >>> C["rocky"] = "road"
225 >>> C["rocky"]["path"] = "/cookie"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000226 >>> print(C.output(header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000227 Cookie: rocky=road; Path=/cookie
Georg Brandl6911e3c2007-09-04 07:15:32 +0000228 >>> print(C.output(attrs=[], header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000229 Cookie: rocky=road
230 >>> C = Cookie.SmartCookie()
231 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000232 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000233 Set-Cookie: vienna=finger
234 Set-Cookie: chips=ahoy
235 >>> C = Cookie.SmartCookie()
236 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000237 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000238 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
239 >>> C = Cookie.SmartCookie()
240 >>> C["oreo"] = "doublestuff"
241 >>> C["oreo"]["path"] = "/"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000242 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000243 Set-Cookie: oreo=doublestuff; Path=/
244 >>> C = Cookie.SmartCookie()
245 >>> C["twix"] = "none for you"
246 >>> C["twix"].value
247 'none for you'
248 >>> C = Cookie.SimpleCookie()
249 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
250 >>> C["string"] = "seven"
251 >>> C["number"].value
252 '7'
253 >>> C["string"].value
254 'seven'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000255 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000256 Set-Cookie: number=7
257 Set-Cookie: string=seven
258 >>> C = Cookie.SerialCookie()
259 >>> C["number"] = 7
260 >>> C["string"] = "seven"
261 >>> C["number"].value
262 7
263 >>> C["string"].value
264 'seven'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000265 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000266 Set-Cookie: number="I7\012."
267 Set-Cookie: string="S'seven'\012p1\012."
268 >>> C = Cookie.SmartCookie()
269 >>> C["number"] = 7
270 >>> C["string"] = "seven"
271 >>> C["number"].value
272 7
273 >>> C["string"].value
274 'seven'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000275 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000276 Set-Cookie: number="I7\012."
277 Set-Cookie: string=seven
278