blob: c2bb80d5d19d82c27a7074f9a1a65a9cabf766c9 [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
Senthil Kumarandf7070a2012-04-22 10:31:52 +080020MSIE 3.0x doesn't follow the character rules outlined in those specs and also
21many current day browsers and servers have relaxed parsing rules when comes to
22Cookie handling. As a result, the parsing rules used are a bit less strict.
23
24The character set, :data:`string.ascii_letters`, :data:`string.digits` and
25``!#$%&'*+-.^_`|~:`` denote the set of valid characters allowed by this module
26in Cookie name (as :attr:`~Morsel.key`).
27
28.. versionchanged:: 3.3
29 Allowed ':' as a valid Cookie name character.
30
Georg Brandl116aa622007-08-15 14:28:22 +000031
Georg Brandlf08a9dd2008-06-10 16:57:31 +000032.. note::
33
34 On encountering an invalid cookie, :exc:`CookieError` is raised, so if your
35 cookie data comes from a browser you should always prepare for invalid data
36 and catch :exc:`CookieError` on parsing.
37
Georg Brandl116aa622007-08-15 14:28:22 +000038
39.. exception:: CookieError
40
41 Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
42 incorrect :mailheader:`Set-Cookie` header, etc.
43
44
45.. class:: BaseCookie([input])
46
47 This class is a dictionary-like object whose keys are strings and whose values
48 are :class:`Morsel` instances. Note that upon setting a key to a value, the
49 value is first converted to a :class:`Morsel` containing the key and the value.
50
51 If *input* is given, it is passed to the :meth:`load` method.
52
53
54.. class:: SimpleCookie([input])
55
56 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
57 and :meth:`value_encode` to be the identity and :func:`str` respectively.
58
59
Georg Brandl116aa622007-08-15 14:28:22 +000060.. seealso::
61
Georg Brandl24420152008-05-26 16:32:26 +000062 Module :mod:`http.cookiejar`
63 HTTP cookie handling for web *clients*. The :mod:`http.cookiejar` and
64 :mod:`http.cookies` modules do not depend on each other.
Georg Brandl116aa622007-08-15 14:28:22 +000065
66 :rfc:`2109` - HTTP State Management Mechanism
67 This is the state management specification implemented by this module.
68
69
70.. _cookie-objects:
71
72Cookie Objects
73--------------
74
75
76.. method:: BaseCookie.value_decode(val)
77
78 Return a decoded value from a string representation. Return value can be any
79 type. This method does nothing in :class:`BaseCookie` --- it exists so it can be
80 overridden.
81
82
83.. method:: BaseCookie.value_encode(val)
84
85 Return an encoded value. *val* can be any type, but return value must be a
86 string. This method does nothing in :class:`BaseCookie` --- it exists so it can
Martin Panterd21e0b52015-10-10 10:36:22 +000087 be overridden.
Georg Brandl116aa622007-08-15 14:28:22 +000088
89 In general, it should be the case that :meth:`value_encode` and
90 :meth:`value_decode` are inverses on the range of *value_decode*.
91
92
Georg Brandl036490d2009-05-17 13:00:36 +000093.. method:: BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\\r\\n')
Georg Brandl116aa622007-08-15 14:28:22 +000094
95 Return a string representation suitable to be sent as HTTP headers. *attrs* and
96 *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used
97 to join the headers together, and is by default the combination ``'\r\n'``
98 (CRLF).
99
Georg Brandl116aa622007-08-15 14:28:22 +0000100
Georg Brandl036490d2009-05-17 13:00:36 +0000101.. method:: BaseCookie.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000102
103 Return an embeddable JavaScript snippet, which, if run on a browser which
104 supports JavaScript, will act the same as if the HTTP headers was sent.
105
106 The meaning for *attrs* is the same as in :meth:`output`.
107
108
109.. method:: BaseCookie.load(rawdata)
110
111 If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
112 found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::
113
114 for k, v in rawdata.items():
115 cookie[k] = v
116
117
118.. _morsel-objects:
119
120Morsel Objects
121--------------
122
123
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000124.. class:: Morsel
Georg Brandl116aa622007-08-15 14:28:22 +0000125
126 Abstract a key/value pair, which has some :rfc:`2109` attributes.
127
128 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
129 :rfc:`2109` attributes, which are
130
131 * ``expires``
132 * ``path``
133 * ``comment``
134 * ``domain``
135 * ``max-age``
136 * ``secure``
137 * ``version``
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000138 * ``httponly``
139
Georg Brandl6faee4e2010-09-21 14:48:28 +0000140 The attribute :attr:`httponly` specifies that the cookie is only transferred
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000141 in HTTP requests, and is not accessible through JavaScript. This is intended
142 to mitigate some forms of cross-site scripting.
Georg Brandl116aa622007-08-15 14:28:22 +0000143
144 The keys are case-insensitive.
145
R David Murray1813c172015-03-29 17:09:21 -0400146 .. versionchanged:: 3.5
147 :meth:`~Morsel.__eq__` now takes :attr:`~Morsel.key` and :attr:`~Morsel.value`
148 into account.
149
Georg Brandl116aa622007-08-15 14:28:22 +0000150
151.. attribute:: Morsel.value
152
153 The value of the cookie.
154
Serhiy Storchaka9c1a9b22015-03-18 10:59:57 +0200155 .. deprecated:: 3.5
R David Murray1813c172015-03-29 17:09:21 -0400156 assigning to ``value``; use :meth:`~Morsel.set` instead.
Serhiy Storchaka9c1a9b22015-03-18 10:59:57 +0200157
Georg Brandl116aa622007-08-15 14:28:22 +0000158
159.. attribute:: Morsel.coded_value
160
161 The encoded value of the cookie --- this is what should be sent.
162
Serhiy Storchaka9c1a9b22015-03-18 10:59:57 +0200163 .. deprecated:: 3.5
R David Murray1813c172015-03-29 17:09:21 -0400164 assigning to ``coded_value``; use :meth:`~Morsel.set` instead.
Serhiy Storchaka9c1a9b22015-03-18 10:59:57 +0200165
Georg Brandl116aa622007-08-15 14:28:22 +0000166
167.. attribute:: Morsel.key
168
169 The name of the cookie.
170
Serhiy Storchaka9c1a9b22015-03-18 10:59:57 +0200171 .. deprecated:: 3.5
R David Murray1813c172015-03-29 17:09:21 -0400172 assigning to ``key``; use :meth:`~Morsel.set` instead.
Serhiy Storchaka9c1a9b22015-03-18 10:59:57 +0200173
Georg Brandl116aa622007-08-15 14:28:22 +0000174
175.. method:: Morsel.set(key, value, coded_value)
176
Senthil Kumarana6bac952011-07-04 11:28:30 -0700177 Set the *key*, *value* and *coded_value* attributes.
Georg Brandl116aa622007-08-15 14:28:22 +0000178
R David Murray1813c172015-03-29 17:09:21 -0400179 .. deprecated:: 3.5
180 The undocumented *LegalChars* parameter is ignored and will be removed in
181 a future version.
182
Georg Brandl116aa622007-08-15 14:28:22 +0000183
184.. method:: Morsel.isReservedKey(K)
185
186 Whether *K* is a member of the set of keys of a :class:`Morsel`.
187
188
Georg Brandl036490d2009-05-17 13:00:36 +0000189.. method:: Morsel.output(attrs=None, header='Set-Cookie:')
Georg Brandl116aa622007-08-15 14:28:22 +0000190
191 Return a string representation of the Morsel, suitable to be sent as an HTTP
192 header. By default, all the attributes are included, unless *attrs* is given, in
193 which case it should be a list of attributes to use. *header* is by default
194 ``"Set-Cookie:"``.
195
196
Georg Brandl036490d2009-05-17 13:00:36 +0000197.. method:: Morsel.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000198
199 Return an embeddable JavaScript snippet, which, if run on a browser which
200 supports JavaScript, will act the same as if the HTTP header was sent.
201
202 The meaning for *attrs* is the same as in :meth:`output`.
203
204
Georg Brandl036490d2009-05-17 13:00:36 +0000205.. method:: Morsel.OutputString(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000206
207 Return a string representing the Morsel, without any surrounding HTTP or
208 JavaScript.
209
210 The meaning for *attrs* is the same as in :meth:`output`.
211
212
R David Murray1813c172015-03-29 17:09:21 -0400213.. method:: Morsel.update(values)
214
215 Update the values in the Morsel dictionary with the values in the dictionary
216 *values*. Raise an error if any of the keys in the *values* dict is not a
217 valid :rfc:`2109` attribute.
218
219 .. versionchanged:: 3.5
220 an error is raised for invalid keys.
221
222
223.. method:: Morsel.copy(value)
224
225 Return a shallow copy of the Morsel object.
226
227 .. versionchanged:: 3.5
228 return a Morsel object instead of a dict.
229
230
R David Murrayba6ea9b2015-03-30 11:48:50 -0400231.. method:: Morsel.setdefault(key, value=None)
232
233 Raise an error if key is not a valid :rfc:`2109` attribute, otherwise
234 behave the same as :meth:`dict.setdefault`.
235
236
Georg Brandl116aa622007-08-15 14:28:22 +0000237.. _cookie-example:
238
239Example
240-------
241
Georg Brandl24420152008-05-26 16:32:26 +0000242The following example demonstrates how to use the :mod:`http.cookies` module.
Christian Heimesfe337bf2008-03-23 21:54:12 +0000243
244.. doctest::
245 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000246
Georg Brandl24420152008-05-26 16:32:26 +0000247 >>> from http import cookies
248 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000249 >>> C["fig"] = "newton"
250 >>> C["sugar"] = "wafer"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000251 >>> print(C) # generate HTTP headers
Georg Brandl116aa622007-08-15 14:28:22 +0000252 Set-Cookie: fig=newton
Christian Heimesfe337bf2008-03-23 21:54:12 +0000253 Set-Cookie: sugar=wafer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000254 >>> print(C.output()) # same thing
Georg Brandl116aa622007-08-15 14:28:22 +0000255 Set-Cookie: fig=newton
Christian Heimesfe337bf2008-03-23 21:54:12 +0000256 Set-Cookie: sugar=wafer
Georg Brandl61013952008-05-28 15:56:30 +0000257 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000258 >>> C["rocky"] = "road"
259 >>> C["rocky"]["path"] = "/cookie"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000260 >>> print(C.output(header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000261 Cookie: rocky=road; Path=/cookie
Georg Brandl6911e3c2007-09-04 07:15:32 +0000262 >>> print(C.output(attrs=[], header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000263 Cookie: rocky=road
Georg Brandl61013952008-05-28 15:56:30 +0000264 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000265 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000266 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000267 Set-Cookie: chips=ahoy
Christian Heimesfe337bf2008-03-23 21:54:12 +0000268 Set-Cookie: vienna=finger
Georg Brandl61013952008-05-28 15:56:30 +0000269 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000270 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000271 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000272 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Georg Brandl61013952008-05-28 15:56:30 +0000273 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000274 >>> C["oreo"] = "doublestuff"
275 >>> C["oreo"]["path"] = "/"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000276 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000277 Set-Cookie: oreo=doublestuff; Path=/
Georg Brandl61013952008-05-28 15:56:30 +0000278 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000279 >>> C["twix"] = "none for you"
280 >>> C["twix"].value
281 'none for you'
Georg Brandl24420152008-05-26 16:32:26 +0000282 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000283 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
284 >>> C["string"] = "seven"
285 >>> C["number"].value
286 '7'
287 >>> C["string"].value
288 'seven'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000289 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000290 Set-Cookie: number=7
291 Set-Cookie: string=seven