1 :mod:`Cookie` --- HTTP state management
2 =======================================
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>
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
15 The :mod:`Cookie` module defines classes for abstracting the concept of
16 cookies, an HTTP state management mechanism. It supports both simple string-only
17 cookies, and provides an abstraction for having any serializable data-type as
20 The module formerly strictly applied the parsing rules described in the
21 :rfc:`2109` and :rfc:`2068` specifications. It has since been discovered that
22 MSIE 3.0x doesn't follow the character rules outlined in those specs. As a
23 result, the parsing rules used are a bit less strict.
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.
32 .. exception:: CookieError
34 Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
35 incorrect :mailheader:`Set-Cookie` header, etc.
38 .. class:: BaseCookie([input])
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.
44 If *input* is given, it is passed to the :meth:`load` method.
47 .. class:: SimpleCookie([input])
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.
53 .. class:: SerialCookie([input])
55 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
56 and :meth:`value_encode` to be the :func:`pickle.loads` and
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.
65 .. class:: SmartCookie([input])
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.
73 The same security warning from :class:`SerialCookie` applies here.
75 A further security note is warranted. For backwards compatibility, the
76 :mod:`Cookie` module exports a class named :class:`Cookie` which is just an
77 alias for :class:`SmartCookie`. This is probably a mistake and will likely be
78 removed in a future version. You should not use the :class:`Cookie` class in
79 your applications, for the same reason why you should not use the
80 :class:`SerialCookie` class.
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.
89 :rfc:`2109` - HTTP State Management Mechanism
90 This is the state management specification implemented by this module.
99 .. method:: BaseCookie.value_decode(val)
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
106 .. method:: BaseCookie.value_encode(val)
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
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*.
116 .. method:: BaseCookie.output([attrs[, header[, sep]]])
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'``
123 .. versionchanged:: 2.5
124 The default separator has been changed from ``'\n'`` to match the cookie
128 .. method:: BaseCookie.js_output([attrs])
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.
133 The meaning for *attrs* is the same as in :meth:`output`.
136 .. method:: BaseCookie.load(rawdata)
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::
141 for k, v in rawdata.items():
153 Abstract a key/value pair, which has some :rfc:`2109` attributes.
155 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
156 :rfc:`2109` attributes, which are
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.
171 The keys are case-insensitive.
173 .. versionadded:: 2.6
174 The :attr:`httponly` attribute was added.
177 .. attribute:: Morsel.value
179 The value of the cookie.
182 .. attribute:: Morsel.coded_value
184 The encoded value of the cookie --- this is what should be sent.
187 .. attribute:: Morsel.key
189 The name of the cookie.
192 .. method:: Morsel.set(key, value, coded_value)
194 Set the *key*, *value* and *coded_value* members.
197 .. method:: Morsel.isReservedKey(K)
199 Whether *K* is a member of the set of keys of a :class:`Morsel`.
202 .. method:: Morsel.output([attrs[, header]])
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
210 .. method:: Morsel.js_output([attrs])
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.
215 The meaning for *attrs* is the same as in :meth:`output`.
218 .. method:: Morsel.OutputString([attrs])
220 Return a string representing the Morsel, without any surrounding HTTP or
223 The meaning for *attrs* is the same as in :meth:`output`.
231 The following example demonstrates how to use the :mod:`Cookie` module.
234 :options: +NORMALIZE_WHITESPACE
237 >>> C = Cookie.SimpleCookie()
238 >>> C = Cookie.SerialCookie()
239 >>> C = Cookie.SmartCookie()
240 >>> C["fig"] = "newton"
241 >>> C["sugar"] = "wafer"
242 >>> print C # generate HTTP headers
243 Set-Cookie: fig=newton
244 Set-Cookie: sugar=wafer
245 >>> print C.output() # same thing
246 Set-Cookie: fig=newton
247 Set-Cookie: sugar=wafer
248 >>> C = Cookie.SmartCookie()
249 >>> C["rocky"] = "road"
250 >>> C["rocky"]["path"] = "/cookie"
251 >>> print C.output(header="Cookie:")
252 Cookie: rocky=road; Path=/cookie
253 >>> print C.output(attrs=[], header="Cookie:")
255 >>> C = Cookie.SmartCookie()
256 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
258 Set-Cookie: chips=ahoy
259 Set-Cookie: vienna=finger
260 >>> C = Cookie.SmartCookie()
261 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
263 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
264 >>> C = Cookie.SmartCookie()
265 >>> C["oreo"] = "doublestuff"
266 >>> C["oreo"]["path"] = "/"
268 Set-Cookie: oreo=doublestuff; Path=/
269 >>> C = Cookie.SmartCookie()
270 >>> C["twix"] = "none for you"
273 >>> C = Cookie.SimpleCookie()
274 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
275 >>> C["string"] = "seven"
276 >>> C["number"].value
278 >>> C["string"].value
282 Set-Cookie: string=seven
283 >>> C = Cookie.SerialCookie()
285 >>> C["string"] = "seven"
286 >>> C["number"].value
288 >>> C["string"].value
291 Set-Cookie: number="I7\012."
292 Set-Cookie: string="S'seven'\012p1\012."
293 >>> C = Cookie.SmartCookie()
295 >>> C["string"] = "seven"
296 >>> C["number"].value
298 >>> C["string"].value
301 Set-Cookie: number="I7\012."
302 Set-Cookie: string=seven