Debian Codegraph @

Doc/library/http.cookies.rst

raw
1 :mod:`!http.cookies` --- HTTP state management
2 ==============================================
3
4 .. module:: http.cookies
5 :synopsis: Support for HTTP state management (cookies).
6
7 .. moduleauthor:: Timothy O'Malley <[email protected]>
8 .. sectionauthor:: Moshe Zadka <[email protected]>
9
10 **Source code:** :source:`Lib/http/cookies.py`
11
12 --------------
13
14 The :mod:`http.cookies` module defines classes for abstracting the concept of
15 cookies, an HTTP state management mechanism. It supports both simple string-only
16 cookies, and provides an abstraction for having any serializable data-type as
17 cookie value.
18
19 The module formerly strictly applied the parsing rules described in the
20 :rfc:`2109` and :rfc:`2068` specifications. It has since been discovered that
21 MSIE 3.0x didn't follow the character rules outlined in those specs; many
22 current-day browsers and servers have also relaxed parsing rules when it comes
23 to cookie handling. As a result, this module now uses parsing rules that are a
24 bit less strict than they once were.
25
26 The character set, :data:`string.ascii_letters`, :data:`string.digits` and
27 ``!#$%&'*+-.^_`|~:`` denote the set of valid characters allowed by this module
28 in a cookie name (as :attr:`~Morsel.key`).
29
30 .. versionchanged:: 3.3
31 Allowed ':' as a valid cookie name character.
32
33
34 .. note::
35
36 On encountering an invalid cookie, :exc:`CookieError` is raised, so if your
37 cookie data comes from a browser you should always prepare for invalid data
38 and catch :exc:`CookieError` on parsing.
39
40
41 .. exception:: CookieError
42
43 Exception failing because of :rfc:`2109` invalidity: incorrect attributes,
44 incorrect :mailheader:`Set-Cookie` header, etc.
45
46
47 .. class:: BaseCookie([input])
48
49 This class is a dictionary-like object whose keys are strings and whose values
50 are :class:`Morsel` instances. Note that upon setting a key to a value, the
51 value is first converted to a :class:`Morsel` containing the key and the value.
52
53 If *input* is given, it is passed to the :meth:`load` method.
54
55
56 .. class:: SimpleCookie([input])
57
58 This class derives from :class:`BaseCookie` and overrides :meth:`~BaseCookie.value_decode`
59 and :meth:`~BaseCookie.value_encode`. :class:`!SimpleCookie` supports
60 strings as cookie values. When setting the value, :class:`!SimpleCookie`
61 calls the builtin :func:`str` to convert
62 the value to a string. Values received from HTTP are kept as strings.
63
64 .. seealso::
65
66 Module :mod:`http.cookiejar`
67 HTTP cookie handling for web *clients*. The :mod:`http.cookiejar` and
68 :mod:`http.cookies` modules do not depend on each other.
69
70 :rfc:`2109` - HTTP State Management Mechanism
71 This is the state management specification implemented by this module.
72
73
74 .. _cookie-objects:
75
76 Cookie Objects
77 --------------
78
79
80 .. method:: BaseCookie.value_decode(val)
81
82 Return a tuple ``(real_value, coded_value)`` from a string representation.
83 ``real_value`` can be any type. This method does no decoding in
84 :class:`BaseCookie` --- it exists so it can be overridden.
85
86
87 .. method:: BaseCookie.value_encode(val)
88
89 Return a tuple ``(real_value, coded_value)``. *val* can be any type, but
90 ``coded_value`` will always be converted to a string.
91 This method does no encoding in :class:`BaseCookie` --- it exists so it can
92 be overridden.
93
94 In general, it should be the case that :meth:`value_encode` and
95 :meth:`value_decode` are inverses on the range of *value_decode*.
96
97
98 .. method:: BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\r\n')
99
100 Return a string representation suitable to be sent as HTTP headers. *attrs* and
101 *header* are sent to each :class:`Morsel`'s :meth:`~Morsel.output` method. *sep* is used
102 to join the headers together, and is by default the combination ``'\r\n'``
103 (CRLF).
104
105
106 .. method:: BaseCookie.js_output(attrs=None)
107
108 Return an embeddable JavaScript snippet, which, if run on a browser which
109 supports JavaScript, will act the same as if the HTTP headers was sent.
110
111 The meaning for *attrs* is the same as in :meth:`output`.
112
113
114 .. method:: BaseCookie.load(rawdata)
115
116 If *rawdata* is a string, parse it as an ``HTTP_COOKIE`` and add the values
117 found there as :class:`Morsel`\ s. If it is a dictionary, it is equivalent to::
118
119 for k, v in rawdata.items():
120 cookie[k] = v
121
122
123 .. _morsel-objects:
124
125 Morsel Objects
126 --------------
127
128
129 .. class:: Morsel
130
131 Abstract a key/value pair, which has some :rfc:`2109` attributes.
132
133 Morsels are dictionary-like objects, whose set of keys is constant --- the valid
134 :rfc:`2109` attributes, which are:
135
136 .. attribute:: expires
137 path
138 comment
139 domain
140 max-age
141 secure
142 version
143 httponly
144 samesite
145
146 The attribute :attr:`httponly` specifies that the cookie is only transferred
147 in HTTP requests, and is not accessible through JavaScript. This is intended
148 to mitigate some forms of cross-site scripting.
149
150 The attribute :attr:`samesite` controls when the browser sends the cookie with
151 cross-site requests. This helps to mitigate CSRF attacks. Valid values are
152 "Strict" (only sent with same-site requests), "Lax" (sent with same-site
153 requests and top-level navigations), and "None" (sent with same-site and
154 cross-site requests). When using "None", the "secure" attribute must also
155 be set, as required by modern browsers.
156
157 The keys are case-insensitive and their default value is ``''``.
158
159 .. versionchanged:: 3.5
160 :meth:`!__eq__` now takes :attr:`~Morsel.key` and :attr:`~Morsel.value`
161 into account.
162
163 .. versionchanged:: 3.7
164 Attributes :attr:`~Morsel.key`, :attr:`~Morsel.value` and
165 :attr:`~Morsel.coded_value` are read-only. Use :meth:`~Morsel.set` for
166 setting them.
167
168 .. versionchanged:: 3.8
169 Added support for the :attr:`samesite` attribute.
170
171
172 .. attribute:: Morsel.value
173
174 The value of the cookie.
175
176
177 .. attribute:: Morsel.coded_value
178
179 The encoded value of the cookie --- this is what should be sent.
180
181
182 .. attribute:: Morsel.key
183
184 The name of the cookie.
185
186
187 .. method:: Morsel.set(key, value, coded_value)
188
189 Set the *key*, *value* and *coded_value* attributes.
190
191
192 .. method:: Morsel.isReservedKey(K)
193
194 Whether *K* is a member of the set of keys of a :class:`Morsel`.
195
196
197 .. method:: Morsel.output(attrs=None, header='Set-Cookie:')
198
199 Return a string representation of the Morsel, suitable to be sent as an HTTP
200 header. By default, all the attributes are included, unless *attrs* is given, in
201 which case it should be a list of attributes to use. *header* is by default
202 ``"Set-Cookie:"``.
203
204
205 .. method:: Morsel.js_output(attrs=None)
206
207 Return an embeddable JavaScript snippet, which, if run on a browser which
208 supports JavaScript, will act the same as if the HTTP header was sent.
209
210 The meaning for *attrs* is the same as in :meth:`output`.
211
212
213 .. method:: Morsel.OutputString(attrs=None)
214
215 Return a string representing the Morsel, without any surrounding HTTP or
216 JavaScript.
217
218 The meaning for *attrs* is the same as in :meth:`output`.
219
220
221 .. method:: Morsel.update(values)
222
223 Update the values in the Morsel dictionary with the values in the dictionary
224 *values*. Raise an error if any of the keys in the *values* dict is not a
225 valid :rfc:`2109` attribute.
226
227 .. versionchanged:: 3.5
228 an error is raised for invalid keys.
229
230
231 .. method:: Morsel.copy(value)
232
233 Return a shallow copy of the Morsel object.
234
235 .. versionchanged:: 3.5
236 return a Morsel object instead of a dict.
237
238
239 .. method:: Morsel.setdefault(key, value=None)
240
241 Raise an error if key is not a valid :rfc:`2109` attribute, otherwise
242 behave the same as :meth:`dict.setdefault`.
243
244
245 .. _cookie-example:
246
247 Example
248 -------
249
250 The following example demonstrates how to use the :mod:`http.cookies` module.
251
252 .. doctest::
253 :options: +NORMALIZE_WHITESPACE
254
255 >>> from http import cookies
256 >>> C = cookies.SimpleCookie()
257 >>> C["fig"] = "newton"
258 >>> C["sugar"] = "wafer"
259 >>> print(C) # generate HTTP headers
260 Set-Cookie: fig=newton
261 Set-Cookie: sugar=wafer
262 >>> print(C.output()) # same thing
263 Set-Cookie: fig=newton
264 Set-Cookie: sugar=wafer
265 >>> C = cookies.SimpleCookie()
266 >>> C["rocky"] = "road"
267 >>> C["rocky"]["path"] = "/cookie"
268 >>> print(C.output(header="Cookie:"))
269 Cookie: rocky=road; Path=/cookie
270 >>> print(C.output(attrs=[], header="Cookie:"))
271 Cookie: rocky=road
272 >>> C = cookies.SimpleCookie()
273 >>> C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
274 >>> print(C)
275 Set-Cookie: chips=ahoy
276 Set-Cookie: vienna=finger
277 >>> C = cookies.SimpleCookie()
278 >>> C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=;";')
279 >>> print(C)
280 Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=;"
281 >>> C = cookies.SimpleCookie()
282 >>> C["oreo"] = "doublestuff"
283 >>> C["oreo"]["path"] = "/"
284 >>> print(C)
285 Set-Cookie: oreo=doublestuff; Path=/
286 >>> C = cookies.SimpleCookie()
287 >>> C["twix"] = "none for you"
288 >>> C["twix"].value
289 'none for you'
290 >>> C = cookies.SimpleCookie()
291 >>> C["number"] = 7 # equivalent to C["number"] = str(7)
292 >>> C["string"] = "seven"
293 >>> C["number"].value
294 '7'
295 >>> C["string"].value
296 'seven'
297 >>> print(C)
298 Set-Cookie: number=7
299 Set-Cookie: string=seven