blob: 5ae3fd40de74033e6924dcbe3f9eb3dac4e3551e [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 Kumarana42665f2012-04-22 10:30:17 +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
Georg Brandl116aa622007-08-15 14:28:22 +000028
Georg Brandlf08a9dd2008-06-10 16:57:31 +000029.. note::
30
31 On encountering an invalid cookie, :exc:`CookieError` is raised, so if your
32 cookie data comes from a browser you should always prepare for invalid data
33 and catch :exc:`CookieError` on parsing.
34
Georg Brandl116aa622007-08-15 14:28:22 +000035
36.. exception:: CookieError
37
38 Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
39 incorrect :mailheader:`Set-Cookie` header, etc.
40
41
42.. class:: BaseCookie([input])
43
44 This class is a dictionary-like object whose keys are strings and whose values
45 are :class:`Morsel` instances. Note that upon setting a key to a value, the
46 value is first converted to a :class:`Morsel` containing the key and the value.
47
48 If *input* is given, it is passed to the :meth:`load` method.
49
50
51.. class:: SimpleCookie([input])
52
53 This class derives from :class:`BaseCookie` and overrides :meth:`value_decode`
54 and :meth:`value_encode` to be the identity and :func:`str` respectively.
55
56
Georg Brandl116aa622007-08-15 14:28:22 +000057.. seealso::
58
Georg Brandl24420152008-05-26 16:32:26 +000059 Module :mod:`http.cookiejar`
60 HTTP cookie handling for web *clients*. The :mod:`http.cookiejar` and
61 :mod:`http.cookies` modules do not depend on each other.
Georg Brandl116aa622007-08-15 14:28:22 +000062
63 :rfc:`2109` - HTTP State Management Mechanism
64 This is the state management specification implemented by this module.
65
66
67.. _cookie-objects:
68
69Cookie Objects
70--------------
71
72
73.. method:: BaseCookie.value_decode(val)
74
75 Return a decoded value from a string representation. Return value can be any
76 type. This method does nothing in :class:`BaseCookie` --- it exists so it can be
77 overridden.
78
79
80.. method:: BaseCookie.value_encode(val)
81
82 Return an encoded value. *val* can be any type, but return value must be a
83 string. This method does nothing in :class:`BaseCookie` --- it exists so it can
84 be overridden
85
86 In general, it should be the case that :meth:`value_encode` and
87 :meth:`value_decode` are inverses on the range of *value_decode*.
88
89
Georg Brandl036490d2009-05-17 13:00:36 +000090.. method:: BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\\r\\n')
Georg Brandl116aa622007-08-15 14:28:22 +000091
92 Return a string representation suitable to be sent as HTTP headers. *attrs* and
93 *header* are sent to each :class:`Morsel`'s :meth:`output` method. *sep* is used
94 to join the headers together, and is by default the combination ``'\r\n'``
95 (CRLF).
96
Georg Brandl116aa622007-08-15 14:28:22 +000097
Georg Brandl036490d2009-05-17 13:00:36 +000098.. method:: BaseCookie.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +000099
100 Return an embeddable JavaScript snippet, which, if run on a browser which
101 supports JavaScript, will act the same as if the HTTP headers was sent.
102
103 The meaning for *attrs* is the same as in :meth:`output`.
104
105
106.. method:: BaseCookie.load(rawdata)
107
108 If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
109 found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::
110
111 for k, v in rawdata.items():
112 cookie[k] = v
113
114
115.. _morsel-objects:
116
117Morsel Objects
118--------------
119
120
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000121.. class:: Morsel
Georg Brandl116aa622007-08-15 14:28:22 +0000122
123 Abstract a key/value pair, which has some :rfc:`2109` attributes.
124
125 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
126 :rfc:`2109` attributes, which are
127
128 * ``expires``
129 * ``path``
130 * ``comment``
131 * ``domain``
132 * ``max-age``
133 * ``secure``
134 * ``version``
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000135 * ``httponly``
136
Georg Brandl6faee4e2010-09-21 14:48:28 +0000137 The attribute :attr:`httponly` specifies that the cookie is only transferred
Benjamin Peterson35e661c2008-09-06 19:37:35 +0000138 in HTTP requests, and is not accessible through JavaScript. This is intended
139 to mitigate some forms of cross-site scripting.
Georg Brandl116aa622007-08-15 14:28:22 +0000140
141 The keys are case-insensitive.
142
143
144.. attribute:: Morsel.value
145
146 The value of the cookie.
147
148
149.. attribute:: Morsel.coded_value
150
151 The encoded value of the cookie --- this is what should be sent.
152
153
154.. attribute:: Morsel.key
155
156 The name of the cookie.
157
158
159.. method:: Morsel.set(key, value, coded_value)
160
Senthil Kumarana6bac952011-07-04 11:28:30 -0700161 Set the *key*, *value* and *coded_value* attributes.
Georg Brandl116aa622007-08-15 14:28:22 +0000162
163
164.. method:: Morsel.isReservedKey(K)
165
166 Whether *K* is a member of the set of keys of a :class:`Morsel`.
167
168
Georg Brandl036490d2009-05-17 13:00:36 +0000169.. method:: Morsel.output(attrs=None, header='Set-Cookie:')
Georg Brandl116aa622007-08-15 14:28:22 +0000170
171 Return a string representation of the Morsel, suitable to be sent as an HTTP
172 header. By default, all the attributes are included, unless *attrs* is given, in
173 which case it should be a list of attributes to use. *header* is by default
174 ``"Set-Cookie:"``.
175
176
Georg Brandl036490d2009-05-17 13:00:36 +0000177.. method:: Morsel.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000178
179 Return an embeddable JavaScript snippet, which, if run on a browser which
180 supports JavaScript, will act the same as if the HTTP header was sent.
181
182 The meaning for *attrs* is the same as in :meth:`output`.
183
184
Georg Brandl036490d2009-05-17 13:00:36 +0000185.. method:: Morsel.OutputString(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000186
187 Return a string representing the Morsel, without any surrounding HTTP or
188 JavaScript.
189
190 The meaning for *attrs* is the same as in :meth:`output`.
191
192
193.. _cookie-example:
194
195Example
196-------
197
Georg Brandl24420152008-05-26 16:32:26 +0000198The following example demonstrates how to use the :mod:`http.cookies` module.
Christian Heimesfe337bf2008-03-23 21:54:12 +0000199
200.. doctest::
201 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000202
Georg Brandl24420152008-05-26 16:32:26 +0000203 >>> from http import cookies
204 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000205 >>> C["fig"] = "newton"
206 >>> C["sugar"] = "wafer"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000207 >>> print(C) # generate HTTP headers
Georg Brandl116aa622007-08-15 14:28:22 +0000208 Set-Cookie: fig=newton
Christian Heimesfe337bf2008-03-23 21:54:12 +0000209 Set-Cookie: sugar=wafer
Georg Brandl6911e3c2007-09-04 07:15:32 +0000210 >>> print(C.output()) # same thing
Georg Brandl116aa622007-08-15 14:28:22 +0000211 Set-Cookie: fig=newton
Christian Heimesfe337bf2008-03-23 21:54:12 +0000212 Set-Cookie: sugar=wafer
Georg Brandl61013952008-05-28 15:56:30 +0000213 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000214 >>> C["rocky"] = "road"
215 >>> C["rocky"]["path"] = "/cookie"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000216 >>> print(C.output(header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000217 Cookie: rocky=road; Path=/cookie
Georg Brandl6911e3c2007-09-04 07:15:32 +0000218 >>> print(C.output(attrs=[], header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000219 Cookie: rocky=road
Georg Brandl61013952008-05-28 15:56:30 +0000220 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000221 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000222 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000223 Set-Cookie: chips=ahoy
Christian Heimesfe337bf2008-03-23 21:54:12 +0000224 Set-Cookie: vienna=finger
Georg Brandl61013952008-05-28 15:56:30 +0000225 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000226 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000227 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000228 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Georg Brandl61013952008-05-28 15:56:30 +0000229 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000230 >>> C["oreo"] = "doublestuff"
231 >>> C["oreo"]["path"] = "/"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000232 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000233 Set-Cookie: oreo=doublestuff; Path=/
Georg Brandl61013952008-05-28 15:56:30 +0000234 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000235 >>> C["twix"] = "none for you"
236 >>> C["twix"].value
237 'none for you'
Georg Brandl24420152008-05-26 16:32:26 +0000238 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000239 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
240 >>> C["string"] = "seven"
241 >>> C["number"].value
242 '7'
243 >>> C["string"].value
244 'seven'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000245 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000246 Set-Cookie: number=7
247 Set-Cookie: string=seven