Issue #5170: Fixed regression caused when fixing #5768.
[python.git] / Doc / library / cookie.rst
blobb6a85f5dffd7711dd837de6718c91264e5b28a39
1 :mod:`Cookie` --- HTTP state management
2 =======================================
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>
9 .. 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.
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
18 cookie value.
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.
25 .. note::
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
57    :func:`pickle.dumps`.
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.
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.
72    .. deprecated:: 2.3
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.
83 .. seealso::
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.
93 .. _cookie-objects:
95 Cookie Objects
96 --------------
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
103    overridden.
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
110    be overridden
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'``
121    (CRLF).
123    .. versionchanged:: 2.5
124       The default separator has been changed from ``'\n'`` to match the cookie
125       specification.
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():
142           cookie[k] = v
145 .. _morsel-objects:
147 Morsel Objects
148 --------------
151 .. class:: Morsel
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
158    * ``expires``
159    * ``path``
160    * ``comment``
161    * ``domain``
162    * ``max-age``
163    * ``secure``
164    * ``version``
165    * ``httponly``
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
207    ``"Set-Cookie:"``.
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
221    JavaScript.
223    The meaning for *attrs* is the same as in :meth:`output`.
226 .. _cookie-example:
228 Example
229 -------
231 The following example demonstrates how to use the :mod:`Cookie` module.
233 .. doctest::
234    :options: +NORMALIZE_WHITESPACE
236    >>> import Cookie
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:")
254    Cookie: rocky=road
255    >>> C = Cookie.SmartCookie()
256    >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
257    >>> print C
258    Set-Cookie: chips=ahoy
259    Set-Cookie: vienna=finger
260    >>> C = Cookie.SmartCookie()
261    >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
262    >>> print C
263    Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
264    >>> C = Cookie.SmartCookie()
265    >>> C["oreo"] = "doublestuff"
266    >>> C["oreo"]["path"] = "/"
267    >>> print C
268    Set-Cookie: oreo=doublestuff; Path=/
269    >>> C = Cookie.SmartCookie()
270    >>> C["twix"] = "none for you"
271    >>> C["twix"].value
272    '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
277    '7'
278    >>> C["string"].value
279    'seven'
280    >>> print C
281    Set-Cookie: number=7
282    Set-Cookie: string=seven
283    >>> C = Cookie.SerialCookie()
284    >>> C["number"] = 7
285    >>> C["string"] = "seven"
286    >>> C["number"].value
287    7
288    >>> C["string"].value
289    'seven'
290    >>> print C
291    Set-Cookie: number="I7\012."
292    Set-Cookie: string="S'seven'\012p1\012."
293    >>> C = Cookie.SmartCookie()
294    >>> C["number"] = 7
295    >>> C["string"] = "seven"
296    >>> C["number"].value
297    7
298    >>> C["string"].value
299    'seven'
300    >>> print C
301    Set-Cookie: number="I7\012."
302    Set-Cookie: string=seven