blob: 646f2e88602bb7466f5d66e6d66c93c0b7614073 [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
87 be overridden
88
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
146
147.. attribute:: Morsel.value
148
149 The value of the cookie.
150
151
152.. attribute:: Morsel.coded_value
153
154 The encoded value of the cookie --- this is what should be sent.
155
156
157.. attribute:: Morsel.key
158
159 The name of the cookie.
160
161
162.. method:: Morsel.set(key, value, coded_value)
163
Senthil Kumarana6bac952011-07-04 11:28:30 -0700164 Set the *key*, *value* and *coded_value* attributes.
Georg Brandl116aa622007-08-15 14:28:22 +0000165
166
167.. method:: Morsel.isReservedKey(K)
168
169 Whether *K* is a member of the set of keys of a :class:`Morsel`.
170
171
Georg Brandl036490d2009-05-17 13:00:36 +0000172.. method:: Morsel.output(attrs=None, header='Set-Cookie:')
Georg Brandl116aa622007-08-15 14:28:22 +0000173
174 Return a string representation of the Morsel, suitable to be sent as an HTTP
175 header. By default, all the attributes are included, unless *attrs* is given, in
176 which case it should be a list of attributes to use. *header* is by default
177 ``"Set-Cookie:"``.
178
179
Georg Brandl036490d2009-05-17 13:00:36 +0000180.. method:: Morsel.js_output(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000181
182 Return an embeddable JavaScript snippet, which, if run on a browser which
183 supports JavaScript, will act the same as if the HTTP header was sent.
184
185 The meaning for *attrs* is the same as in :meth:`output`.
186
187
Georg Brandl036490d2009-05-17 13:00:36 +0000188.. method:: Morsel.OutputString(attrs=None)
Georg Brandl116aa622007-08-15 14:28:22 +0000189
190 Return a string representing the Morsel, without any surrounding HTTP or
191 JavaScript.
192
193 The meaning for *attrs* is the same as in :meth:`output`.
194
195
196.. _cookie-example:
197
198Example
199-------
200
Georg Brandl24420152008-05-26 16:32:26 +0000201The following example demonstrates how to use the :mod:`http.cookies` module.
Christian Heimesfe337bf2008-03-23 21:54:12 +0000202
203.. doctest::
204 :options: +NORMALIZE_WHITESPACE
Georg Brandl116aa622007-08-15 14:28:22 +0000205
Georg Brandl24420152008-05-26 16:32:26 +0000206 >>> from http import cookies
207 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000208 >>> C["fig"] = "newton"
209 >>> C["sugar"] = "wafer"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000210 >>> print(C) # generate HTTP headers
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 Brandl6911e3c2007-09-04 07:15:32 +0000213 >>> print(C.output()) # same thing
Georg Brandl116aa622007-08-15 14:28:22 +0000214 Set-Cookie: fig=newton
Christian Heimesfe337bf2008-03-23 21:54:12 +0000215 Set-Cookie: sugar=wafer
Georg Brandl61013952008-05-28 15:56:30 +0000216 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000217 >>> C["rocky"] = "road"
218 >>> C["rocky"]["path"] = "/cookie"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000219 >>> print(C.output(header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000220 Cookie: rocky=road; Path=/cookie
Georg Brandl6911e3c2007-09-04 07:15:32 +0000221 >>> print(C.output(attrs=[], header="Cookie:"))
Georg Brandl116aa622007-08-15 14:28:22 +0000222 Cookie: rocky=road
Georg Brandl61013952008-05-28 15:56:30 +0000223 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000224 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
Georg Brandl6911e3c2007-09-04 07:15:32 +0000225 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000226 Set-Cookie: chips=ahoy
Christian Heimesfe337bf2008-03-23 21:54:12 +0000227 Set-Cookie: vienna=finger
Georg Brandl61013952008-05-28 15:56:30 +0000228 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000229 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
Georg Brandl6911e3c2007-09-04 07:15:32 +0000230 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000231 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
Georg Brandl61013952008-05-28 15:56:30 +0000232 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000233 >>> C["oreo"] = "doublestuff"
234 >>> C["oreo"]["path"] = "/"
Georg Brandl6911e3c2007-09-04 07:15:32 +0000235 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000236 Set-Cookie: oreo=doublestuff; Path=/
Georg Brandl61013952008-05-28 15:56:30 +0000237 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000238 >>> C["twix"] = "none for you"
239 >>> C["twix"].value
240 'none for you'
Georg Brandl24420152008-05-26 16:32:26 +0000241 >>> C = cookies.SimpleCookie()
Georg Brandl116aa622007-08-15 14:28:22 +0000242 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
243 >>> C["string"] = "seven"
244 >>> C["number"].value
245 '7'
246 >>> C["string"].value
247 'seven'
Georg Brandl6911e3c2007-09-04 07:15:32 +0000248 >>> print(C)
Georg Brandl116aa622007-08-15 14:28:22 +0000249 Set-Cookie: number=7
250 Set-Cookie: string=seven