blob: d8a437b362b66aebd5d39aa7eab3587c135fe2aa [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
Raymond Hettinger469271d2011-01-27 20:38:46 +00009**Source code:** :source:`Lib/http/cookies.py`
10
11--------------
Georg Brandl116aa622007-08-15 14:28:22 +000012
Georg Brandl24420152008-05-26 16:32:26 +000013The :mod:`http.cookies` module defines classes for abstracting the concept of
Georg Brandl116aa622007-08-15 14:28:22 +000014cookies, an HTTP state management mechanism. It supports both simple string-only
15cookies, and provides an abstraction for having any serializable data-type as
16cookie value.
17
18The module formerly strictly applied the parsing rules described in the
19:rfc:`2109` and :rfc:`2068` specifications. It has since been discovered that
20MSIE 3.0x doesn't follow the character rules outlined in those specs. As a
21result, the parsing rules used are a bit less strict.
22
Georg Brandlf08a9dd2008-06-10 16:57:31 +000023.. note::
24
25 On encountering an invalid cookie, :exc:`CookieError` is raised, so if your
26 cookie data comes from a browser you should always prepare for invalid data
27 and catch :exc:`CookieError` on parsing.
28
Georg Brandl116aa622007-08-15 14:28:22 +000029
30.. exception:: CookieError
31
32 Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
33 incorrect :mailheader:`Set-Cookie` header, etc.
34
35
36.. class:: BaseCookie([input])
37
38 This class is a dictionary-like object whose keys are strings and whose values
39 are :class:`Morsel` instances. Note that upon setting a key to a value, the
40 value is first converted to a :class:`Morsel` containing the key and the value.
41
42 If *input* is given, it is passed to the :meth:`load` method.
43
44
45.. class:: SimpleCookie([input])
46
47 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
48 and :meth:`value_encode` to be the identity and :func:`str` respectively.
49
50
Georg Brandl116aa622007-08-15 14:28:22 +000051.. seealso::
52
Georg Brandl24420152008-05-26 16:32:26 +000053 Module :mod:`http.cookiejar`
54 HTTP cookie handling for web *clients*. The :mod:`http.cookiejar` and
55 :mod:`http.cookies` modules do not depend on each other.
Georg Brandl116aa622007-08-15 14:28:22 +000056
57 :rfc:`2109` - HTTP State Management Mechanism
58 This is the state management specification implemented by this module.
59
60
61.. _cookie-objects:
62
63Cookie Objects
64--------------
65
66
67.. method:: BaseCookie.value_decode(val)
68
69 Return a decoded value from a string representation. Return value can be any
70 type. This method does nothing in :class:`BaseCookie` --- it exists so it can be
71 overridden.
72
73
74.. method:: BaseCookie.value_encode(val)
75
76 Return an encoded value. *val* can be any type, but return value must be a
77 string. This method does nothing in :class:`BaseCookie` --- it exists so it can
78 be overridden
79
80 In general, it should be the case that :meth:`value_encode` and
81 :meth:`value_decode` are inverses on the range of *value_decode*.
82
83
Georg Brandl036490d2009-05-17 13:00:36 +000084.. method:: BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\\r\\n')
Georg Brandl116aa622007-08-15 14:28:22 +000085
86 Return a string representation suitable to be sent as HTTP headers. *attrs* and
87 *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used
88 to join the headers together, and is by default the combination ``'\r\n'``
89 (CRLF).
90
Georg Brandl116aa622007-08-15 14:28:22 +000091
Georg Brandl036490d2009-05-17 13:00:36 +000092.. method:: BaseCookie.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +000093
94 Return an embeddable JavaScript snippet, which, if run on a browser which
95 supports JavaScript, will act the same as if the HTTP headers was sent.
96
97 The meaning for *attrs* is the same as in :meth:`output`.
98
99
100.. method:: BaseCookie.load(rawdata)
101
102 If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
103 found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::
104
105 for k, v in rawdata.items():
106 cookie[k] = v
107
108
109.. _morsel-objects:
110
111Morsel Objects
112--------------
113
114
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000115.. class:: Morsel
Georg Brandl116aa622007-08-15 14:28:22 +0000116
117 Abstract a key/value pair, which has some :rfc:`2109` attributes.
118
119 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
120 :rfc:`2109` attributes, which are
121
122 * ``expires``
123 * ``path``
124 * ``comment``
125 * ``domain``
126 * ``max-age``
127 * ``secure``
128 * ``version``
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000129 * ``httponly``
130
Georg Brandl6faee4e2010-09-21 14:48:28 +0000131 The attribute :attr:`httponly` specifies that the cookie is only transferred
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000132 in HTTP requests, and is not accessible through JavaScript. This is intended
133 to mitigate some forms of cross-site scripting.
Georg Brandl116aa622007-08-15 14:28:22 +0000134
135 The keys are case-insensitive.
136
137
138.. attribute:: Morsel.value
139
140 The value of the cookie.
141
142
143.. attribute:: Morsel.coded_value
144
145 The encoded value of the cookie --- this is what should be sent.
146
147
148.. attribute:: Morsel.key
149
150 The name of the cookie.
151
152
153.. method:: Morsel.set(key, value, coded_value)
154
155 Set the *key*, *value* and *coded_value* members.
156
157
158.. method:: Morsel.isReservedKey(K)
159
160 Whether *K* is a member of the set of keys of a :class:`Morsel`.
161
162
Georg Brandl036490d2009-05-17 13:00:36 +0000163.. method:: Morsel.output(attrs=None, header='Set-Cookie:')
Georg Brandl116aa622007-08-15 14:28:22 +0000164
165 Return a string representation of the Morsel, suitable to be sent as an HTTP
166 header. By default, all the attributes are included, unless *attrs* is given, in
167 which case it should be a list of attributes to use. *header* is by default
168 ``"Set-Cookie:"``.
169
170
Georg Brandl036490d2009-05-17 13:00:36 +0000171.. method:: Morsel.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000172
173 Return an embeddable JavaScript snippet, which, if run on a browser which
174 supports JavaScript, will act the same as if the HTTP header was sent.
175
176 The meaning for *attrs* is the same as in :meth:`output`.
177
178
Georg Brandl036490d2009-05-17 13:00:36 +0000179.. method:: Morsel.OutputString(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000180
181 Return a string representing the Morsel, without any surrounding HTTP or
182 JavaScript.
183
184 The meaning for *attrs* is the same as in :meth:`output`.
185
186
187.. _cookie-example:
188
189Example
190-------
191
Georg Brandl24420152008-05-26 16:32:26 +0000192The following example demonstrates how to use the :mod:`http.cookies` module.
Christian Heimesfe337bf2008-03-23 21:54:12 +0000193
194.. doctest::
195 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000196
Georg Brandl24420152008-05-26 16:32:26 +0000197 >>> from http import cookies
198 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000199 >>> C["fig"] = "newton"
200 >>> C["sugar"] = "wafer"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000201 >>> print(C) # generate HTTP headers
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 Brandl6911e3c2007-09-04 07:15:32 +0000204 >>> print(C.output()) # same thing
Georg Brandl116aa622007-08-15 14:28:22 +0000205 Set-Cookie: fig=newton
Christian Heimesfe337bf2008-03-23 21:54:12 +0000206 Set-Cookie: sugar=wafer
Georg Brandl61013952008-05-28 15:56:30 +0000207 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000208 >>> C["rocky"] = "road"
209 >>> C["rocky"]["path"] = "/cookie"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000210 >>> print(C.output(header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000211 Cookie: rocky=road; Path=/cookie
Georg Brandl6911e3c2007-09-04 07:15:32 +0000212 >>> print(C.output(attrs=[], header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000213 Cookie: rocky=road
Georg Brandl61013952008-05-28 15:56:30 +0000214 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000215 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000216 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000217 Set-Cookie: chips=ahoy
Christian Heimesfe337bf2008-03-23 21:54:12 +0000218 Set-Cookie: vienna=finger
Georg Brandl61013952008-05-28 15:56:30 +0000219 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000220 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000221 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000222 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Georg Brandl61013952008-05-28 15:56:30 +0000223 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000224 >>> C["oreo"] = "doublestuff"
225 >>> C["oreo"]["path"] = "/"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000226 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000227 Set-Cookie: oreo=doublestuff; Path=/
Georg Brandl61013952008-05-28 15:56:30 +0000228 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000229 >>> C["twix"] = "none for you"
230 >>> C["twix"].value
231 'none for you'
Georg Brandl24420152008-05-26 16:32:26 +0000232 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000233 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
234 >>> C["string"] = "seven"
235 >>> C["number"].value
236 '7'
237 >>> C["string"].value
238 'seven'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000239 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000240 Set-Cookie: number=7
241 Set-Cookie: string=seven