blob: 0151e9449b4a49f04bad9d2432fba34808d602e0 [file] [log] [blame]
Georg Brandl24420152008-05-26 16:32:26 +00001:mod:`http.cookies` --- HTTP state management
2=============================================
Georg Brandl116aa622007-08-15 14:28:22 +00003
Georg Brandl24420152008-05-26 16:32:26 +00004.. module:: http.cookies
Georg Brandl116aa622007-08-15 14:28:22 +00005 :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
9
Georg Brandl24420152008-05-26 16:32:26 +000010The :mod:`http.cookies` module defines classes for abstracting the concept of
Georg Brandl116aa622007-08-15 14:28:22 +000011cookies, an HTTP state management mechanism. It supports both simple string-only
12cookies, and provides an abstraction for having any serializable data-type as
13cookie value.
14
15The module formerly strictly applied the parsing rules described in the
16:rfc:`2109` and :rfc:`2068` specifications. It has since been discovered that
17MSIE 3.0x doesn't follow the character rules outlined in those specs. As a
18result, the parsing rules used are a bit less strict.
19
Georg Brandlf08a9dd2008-06-10 16:57:31 +000020.. note::
21
22 On encountering an invalid cookie, :exc:`CookieError` is raised, so if your
23 cookie data comes from a browser you should always prepare for invalid data
24 and catch :exc:`CookieError` on parsing.
25
Georg Brandl116aa622007-08-15 14:28:22 +000026
27.. exception:: CookieError
28
29 Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
30 incorrect :mailheader:`Set-Cookie` header, etc.
31
32
33.. class:: BaseCookie([input])
34
35 This class is a dictionary-like object whose keys are strings and whose values
36 are :class:`Morsel` instances. Note that upon setting a key to a value, the
37 value is first converted to a :class:`Morsel` containing the key and the value.
38
39 If *input* is given, it is passed to the :meth:`load` method.
40
41
42.. class:: SimpleCookie([input])
43
44 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
45 and :meth:`value_encode` to be the identity and :func:`str` respectively.
46
47
Georg Brandl116aa622007-08-15 14:28:22 +000048.. seealso::
49
Georg Brandl24420152008-05-26 16:32:26 +000050 Module :mod:`http.cookiejar`
51 HTTP cookie handling for web *clients*. The :mod:`http.cookiejar` and
52 :mod:`http.cookies` modules do not depend on each other.
Georg Brandl116aa622007-08-15 14:28:22 +000053
54 :rfc:`2109` - HTTP State Management Mechanism
55 This is the state management specification implemented by this module.
56
57
58.. _cookie-objects:
59
60Cookie Objects
61--------------
62
63
64.. method:: BaseCookie.value_decode(val)
65
66 Return a decoded value from a string representation. Return value can be any
67 type. This method does nothing in :class:`BaseCookie` --- it exists so it can be
68 overridden.
69
70
71.. method:: BaseCookie.value_encode(val)
72
73 Return an encoded value. *val* can be any type, but return value must be a
74 string. This method does nothing in :class:`BaseCookie` --- it exists so it can
75 be overridden
76
77 In general, it should be the case that :meth:`value_encode` and
78 :meth:`value_decode` are inverses on the range of *value_decode*.
79
80
Georg Brandl036490d2009-05-17 13:00:36 +000081.. method:: BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\\r\\n')
Georg Brandl116aa622007-08-15 14:28:22 +000082
83 Return a string representation suitable to be sent as HTTP headers. *attrs* and
84 *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used
85 to join the headers together, and is by default the combination ``'\r\n'``
86 (CRLF).
87
Georg Brandl116aa622007-08-15 14:28:22 +000088
Georg Brandl036490d2009-05-17 13:00:36 +000089.. method:: BaseCookie.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +000090
91 Return an embeddable JavaScript snippet, which, if run on a browser which
92 supports JavaScript, will act the same as if the HTTP headers was sent.
93
94 The meaning for *attrs* is the same as in :meth:`output`.
95
96
97.. method:: BaseCookie.load(rawdata)
98
99 If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
100 found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::
101
102 for k, v in rawdata.items():
103 cookie[k] = v
104
105
106.. _morsel-objects:
107
108Morsel Objects
109--------------
110
111
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000112.. class:: Morsel
Georg Brandl116aa622007-08-15 14:28:22 +0000113
114 Abstract a key/value pair, which has some :rfc:`2109` attributes.
115
116 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
117 :rfc:`2109` attributes, which are
118
119 * ``expires``
120 * ``path``
121 * ``comment``
122 * ``domain``
123 * ``max-age``
124 * ``secure``
125 * ``version``
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000126 * ``httponly``
127
128 The attribute :attr:`httponly` specifies that the cookie is only transfered
129 in HTTP requests, and is not accessible through JavaScript. This is intended
130 to mitigate some forms of cross-site scripting.
Georg Brandl116aa622007-08-15 14:28:22 +0000131
132 The keys are case-insensitive.
133
134
135.. attribute:: Morsel.value
136
137 The value of the cookie.
138
139
140.. attribute:: Morsel.coded_value
141
142 The encoded value of the cookie --- this is what should be sent.
143
144
145.. attribute:: Morsel.key
146
147 The name of the cookie.
148
149
150.. method:: Morsel.set(key, value, coded_value)
151
152 Set the *key*, *value* and *coded_value* members.
153
154
155.. method:: Morsel.isReservedKey(K)
156
157 Whether *K* is a member of the set of keys of a :class:`Morsel`.
158
159
Georg Brandl036490d2009-05-17 13:00:36 +0000160.. method:: Morsel.output(attrs=None, header='Set-Cookie:')
Georg Brandl116aa622007-08-15 14:28:22 +0000161
162 Return a string representation of the Morsel, suitable to be sent as an HTTP
163 header. By default, all the attributes are included, unless *attrs* is given, in
164 which case it should be a list of attributes to use. *header* is by default
165 ``"Set-Cookie:"``.
166
167
Georg Brandl036490d2009-05-17 13:00:36 +0000168.. method:: Morsel.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000169
170 Return an embeddable JavaScript snippet, which, if run on a browser which
171 supports JavaScript, will act the same as if the HTTP header was sent.
172
173 The meaning for *attrs* is the same as in :meth:`output`.
174
175
Georg Brandl036490d2009-05-17 13:00:36 +0000176.. method:: Morsel.OutputString(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000177
178 Return a string representing the Morsel, without any surrounding HTTP or
179 JavaScript.
180
181 The meaning for *attrs* is the same as in :meth:`output`.
182
183
184.. _cookie-example:
185
186Example
187-------
188
Georg Brandl24420152008-05-26 16:32:26 +0000189The following example demonstrates how to use the :mod:`http.cookies` module.
Christian Heimesfe337bf2008-03-23 21:54:12 +0000190
191.. doctest::
192 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000193
Georg Brandl24420152008-05-26 16:32:26 +0000194 >>> from http import cookies
195 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000196 >>> C["fig"] = "newton"
197 >>> C["sugar"] = "wafer"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000198 >>> print(C) # generate HTTP headers
Georg Brandl116aa622007-08-15 14:28:22 +0000199 Set-Cookie: fig=newton
Christian Heimesfe337bf2008-03-23 21:54:12 +0000200 Set-Cookie: sugar=wafer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000201 >>> print(C.output()) # same thing
Georg Brandl116aa622007-08-15 14:28:22 +0000202 Set-Cookie: fig=newton
Christian Heimesfe337bf2008-03-23 21:54:12 +0000203 Set-Cookie: sugar=wafer
Georg Brandl61013952008-05-28 15:56:30 +0000204 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000205 >>> C["rocky"] = "road"
206 >>> C["rocky"]["path"] = "/cookie"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000207 >>> print(C.output(header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000208 Cookie: rocky=road; Path=/cookie
Georg Brandl6911e3c2007-09-04 07:15:32 +0000209 >>> print(C.output(attrs=[], header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000210 Cookie: rocky=road
Georg Brandl61013952008-05-28 15:56:30 +0000211 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000212 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000213 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000214 Set-Cookie: chips=ahoy
Christian Heimesfe337bf2008-03-23 21:54:12 +0000215 Set-Cookie: vienna=finger
Georg Brandl61013952008-05-28 15:56:30 +0000216 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000217 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000218 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000219 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Georg Brandl61013952008-05-28 15:56:30 +0000220 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000221 >>> C["oreo"] = "doublestuff"
222 >>> C["oreo"]["path"] = "/"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000223 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000224 Set-Cookie: oreo=doublestuff; Path=/
Georg Brandl61013952008-05-28 15:56:30 +0000225 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000226 >>> C["twix"] = "none for you"
227 >>> C["twix"].value
228 'none for you'
Georg Brandl24420152008-05-26 16:32:26 +0000229 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000230 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
231 >>> C["string"] = "seven"
232 >>> C["number"].value
233 '7'
234 >>> C["string"].value
235 'seven'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000236 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000237 Set-Cookie: number=7
238 Set-Cookie: string=seven