summaryrefslogtreecommitdiff
path: root/devdocs/python~3.12/library%2Fhttp.cookies.html
blob: 25e1e7e6890fb597f8024aa10ec7cff2fb967304 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
 <span id="http-cookies-http-state-management"></span><h1>http.cookies — HTTP state management</h1> <p><strong>Source code:</strong> <a class="reference external" href="https://github.com/python/cpython/tree/3.12/Lib/http/cookies.py">Lib/http/cookies.py</a></p>  <p>The <a class="reference internal" href="#module-http.cookies" title="http.cookies: Support for HTTP state management (cookies)."><code>http.cookies</code></a> module defines classes for abstracting the concept of cookies, an HTTP state management mechanism. It supports both simple string-only cookies, and provides an abstraction for having any serializable data-type as cookie value.</p> <p>The module formerly strictly applied the parsing rules described in the <span class="target" id="index-0"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2109.html"><strong>RFC 2109</strong></a> and <span class="target" id="index-1"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2068.html"><strong>RFC 2068</strong></a> specifications. It has since been discovered that MSIE 3.0x didn’t follow the character rules outlined in those specs; many current-day browsers and servers have also relaxed parsing rules when it comes to cookie handling. As a result, this module now uses parsing rules that are a bit less strict than they once were.</p> <p>The character set, <a class="reference internal" href="string#string.ascii_letters" title="string.ascii_letters"><code>string.ascii_letters</code></a>, <a class="reference internal" href="string#string.digits" title="string.digits"><code>string.digits</code></a> and <code>!#$%&amp;'*+-.^_`|~:</code> denote the set of valid characters allowed by this module in a cookie name (as <a class="reference internal" href="#http.cookies.Morsel.key" title="http.cookies.Morsel.key"><code>key</code></a>).</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.3: </span>Allowed ‘:’ as a valid cookie name character.</p> </div> <div class="admonition note"> <p class="admonition-title">Note</p> <p>On encountering an invalid cookie, <a class="reference internal" href="#http.cookies.CookieError" title="http.cookies.CookieError"><code>CookieError</code></a> is raised, so if your cookie data comes from a browser you should always prepare for invalid data and catch <a class="reference internal" href="#http.cookies.CookieError" title="http.cookies.CookieError"><code>CookieError</code></a> on parsing.</p> </div> <dl class="py exception"> <dt class="sig sig-object py" id="http.cookies.CookieError">
<code>exception http.cookies.CookieError</code> </dt> <dd>
<p>Exception failing because of <span class="target" id="index-2"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2109.html"><strong>RFC 2109</strong></a> invalidity: incorrect attributes, incorrect <em class="mailheader">Set-Cookie</em> header, etc.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="http.cookies.BaseCookie">
<code>class http.cookies.BaseCookie([input])</code> </dt> <dd>
<p>This class is a dictionary-like object whose keys are strings and whose values are <a class="reference internal" href="#http.cookies.Morsel" title="http.cookies.Morsel"><code>Morsel</code></a> instances. Note that upon setting a key to a value, the value is first converted to a <a class="reference internal" href="#http.cookies.Morsel" title="http.cookies.Morsel"><code>Morsel</code></a> containing the key and the value.</p> <p>If <em>input</em> is given, it is passed to the <a class="reference internal" href="#http.cookies.BaseCookie.load" title="http.cookies.BaseCookie.load"><code>load()</code></a> method.</p> </dd>
</dl> <dl class="py class"> <dt class="sig sig-object py" id="http.cookies.SimpleCookie">
<code>class http.cookies.SimpleCookie([input])</code> </dt> <dd>
<p>This class derives from <a class="reference internal" href="#http.cookies.BaseCookie" title="http.cookies.BaseCookie"><code>BaseCookie</code></a> and overrides <a class="reference internal" href="#http.cookies.BaseCookie.value_decode" title="http.cookies.BaseCookie.value_decode"><code>value_decode()</code></a> and <a class="reference internal" href="#http.cookies.BaseCookie.value_encode" title="http.cookies.BaseCookie.value_encode"><code>value_encode()</code></a>. <code>SimpleCookie</code> supports strings as cookie values. When setting the value, <code>SimpleCookie</code> calls the builtin <a class="reference internal" href="stdtypes#str" title="str"><code>str()</code></a> to convert the value to a string. Values received from HTTP are kept as strings.</p> </dd>
</dl> <div class="admonition seealso"> <p class="admonition-title">See also</p> <dl class="simple"> <dt>
<code>Module</code> <a class="reference internal" href="http.cookiejar#module-http.cookiejar" title="http.cookiejar: Classes for automatic handling of HTTP cookies."><code>http.cookiejar</code></a>
</dt>
<dd>
<p>HTTP cookie handling for web <em>clients</em>. The <a class="reference internal" href="http.cookiejar#module-http.cookiejar" title="http.cookiejar: Classes for automatic handling of HTTP cookies."><code>http.cookiejar</code></a> and <a class="reference internal" href="#module-http.cookies" title="http.cookies: Support for HTTP state management (cookies)."><code>http.cookies</code></a> modules do not depend on each other.</p> </dd> <dt>
<span class="target" id="index-3"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2109.html"><strong>RFC 2109</strong></a> - HTTP State Management Mechanism</dt>
<dd>
<p>This is the state management specification implemented by this module.</p> </dd> </dl> </div> <section id="cookie-objects"> <span id="id1"></span><h2>Cookie Objects</h2> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.BaseCookie.value_decode">
<code>BaseCookie.value_decode(val)</code> </dt> <dd>
<p>Return a tuple <code>(real_value, coded_value)</code> from a string representation. <code>real_value</code> can be any type. This method does no decoding in <a class="reference internal" href="#http.cookies.BaseCookie" title="http.cookies.BaseCookie"><code>BaseCookie</code></a> — it exists so it can be overridden.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.BaseCookie.value_encode">
<code>BaseCookie.value_encode(val)</code> </dt> <dd>
<p>Return a tuple <code>(real_value, coded_value)</code>. <em>val</em> can be any type, but <code>coded_value</code> will always be converted to a string. This method does no encoding in <a class="reference internal" href="#http.cookies.BaseCookie" title="http.cookies.BaseCookie"><code>BaseCookie</code></a> — it exists so it can be overridden.</p> <p>In general, it should be the case that <a class="reference internal" href="#http.cookies.BaseCookie.value_encode" title="http.cookies.BaseCookie.value_encode"><code>value_encode()</code></a> and <a class="reference internal" href="#http.cookies.BaseCookie.value_decode" title="http.cookies.BaseCookie.value_decode"><code>value_decode()</code></a> are inverses on the range of <em>value_decode</em>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.BaseCookie.output">
<code>BaseCookie.output(attrs=None, header='Set-Cookie:', sep='\r\n')</code> </dt> <dd>
<p>Return a string representation suitable to be sent as HTTP headers. <em>attrs</em> and <em>header</em> are sent to each <a class="reference internal" href="#http.cookies.Morsel" title="http.cookies.Morsel"><code>Morsel</code></a>’s <a class="reference internal" href="#http.cookies.BaseCookie.output" title="http.cookies.BaseCookie.output"><code>output()</code></a> method. <em>sep</em> is used to join the headers together, and is by default the combination <code>'\r\n'</code> (CRLF).</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.BaseCookie.js_output">
<code>BaseCookie.js_output(attrs=None)</code> </dt> <dd>
<p>Return an embeddable JavaScript snippet, which, if run on a browser which supports JavaScript, will act the same as if the HTTP headers was sent.</p> <p>The meaning for <em>attrs</em> is the same as in <a class="reference internal" href="#http.cookies.BaseCookie.output" title="http.cookies.BaseCookie.output"><code>output()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.BaseCookie.load">
<code>BaseCookie.load(rawdata)</code> </dt> <dd>
<p>If <em>rawdata</em> is a string, parse it as an <code>HTTP_COOKIE</code> and add the values found there as <a class="reference internal" href="#http.cookies.Morsel" title="http.cookies.Morsel"><code>Morsel</code></a>s. If it is a dictionary, it is equivalent to:</p> <pre data-language="python">for k, v in rawdata.items():
    cookie[k] = v
</pre> </dd>
</dl> </section> <section id="morsel-objects"> <span id="id2"></span><h2>Morsel Objects</h2> <dl class="py class"> <dt class="sig sig-object py" id="http.cookies.Morsel">
<code>class http.cookies.Morsel</code> </dt> <dd>
<p>Abstract a key/value pair, which has some <span class="target" id="index-4"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2109.html"><strong>RFC 2109</strong></a> attributes.</p> <p>Morsels are dictionary-like objects, whose set of keys is constant — the valid <span class="target" id="index-5"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2109.html"><strong>RFC 2109</strong></a> attributes, which are:</p>  <dl class="py attribute"> <dt class="sig sig-object py" id="http.cookies.Morsel.expires">
<code>expires</code> </dt> <dt class="sig sig-object py" id="http.cookies.Morsel.path">
<code>path</code> </dt> <dt class="sig sig-object py" id="http.cookies.Morsel.comment">
<code>comment</code> </dt> <dt class="sig sig-object py" id="http.cookies.Morsel.domain">
<code>domain</code> </dt> <dt class="sig sig-object py"> <span class="sig-name descname">max-age</span>
</dt> <dt class="sig sig-object py" id="http.cookies.Morsel.secure">
<code>secure</code> </dt> <dt class="sig sig-object py" id="http.cookies.Morsel.version">
<code>version</code> </dt> <dt class="sig sig-object py" id="http.cookies.Morsel.httponly">
<code>httponly</code> </dt> <dt class="sig sig-object py" id="http.cookies.Morsel.samesite">
<code>samesite</code> </dt> <dd></dd>
</dl>  <p>The attribute <a class="reference internal" href="#http.cookies.Morsel.httponly" title="http.cookies.Morsel.httponly"><code>httponly</code></a> specifies that the cookie is only transferred in HTTP requests, and is not accessible through JavaScript. This is intended to mitigate some forms of cross-site scripting.</p> <p>The attribute <a class="reference internal" href="#http.cookies.Morsel.samesite" title="http.cookies.Morsel.samesite"><code>samesite</code></a> specifies that the browser is not allowed to send the cookie along with cross-site requests. This helps to mitigate CSRF attacks. Valid values for this attribute are “Strict” and “Lax”.</p> <p>The keys are case-insensitive and their default value is <code>''</code>.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span><code>__eq__()</code> now takes <a class="reference internal" href="#http.cookies.Morsel.key" title="http.cookies.Morsel.key"><code>key</code></a> and <a class="reference internal" href="#http.cookies.Morsel.value" title="http.cookies.Morsel.value"><code>value</code></a> into account.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.7: </span>Attributes <a class="reference internal" href="#http.cookies.Morsel.key" title="http.cookies.Morsel.key"><code>key</code></a>, <a class="reference internal" href="#http.cookies.Morsel.value" title="http.cookies.Morsel.value"><code>value</code></a> and <a class="reference internal" href="#http.cookies.Morsel.coded_value" title="http.cookies.Morsel.coded_value"><code>coded_value</code></a> are read-only. Use <a class="reference internal" href="#http.cookies.Morsel.set" title="http.cookies.Morsel.set"><code>set()</code></a> for setting them.</p> </div> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.8: </span>Added support for the <a class="reference internal" href="#http.cookies.Morsel.samesite" title="http.cookies.Morsel.samesite"><code>samesite</code></a> attribute.</p> </div> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.cookies.Morsel.value">
<code>Morsel.value</code> </dt> <dd>
<p>The value of the cookie.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.cookies.Morsel.coded_value">
<code>Morsel.coded_value</code> </dt> <dd>
<p>The encoded value of the cookie — this is what should be sent.</p> </dd>
</dl> <dl class="py attribute"> <dt class="sig sig-object py" id="http.cookies.Morsel.key">
<code>Morsel.key</code> </dt> <dd>
<p>The name of the cookie.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.Morsel.set">
<code>Morsel.set(key, value, coded_value)</code> </dt> <dd>
<p>Set the <em>key</em>, <em>value</em> and <em>coded_value</em> attributes.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.Morsel.isReservedKey">
<code>Morsel.isReservedKey(K)</code> </dt> <dd>
<p>Whether <em>K</em> is a member of the set of keys of a <a class="reference internal" href="#http.cookies.Morsel" title="http.cookies.Morsel"><code>Morsel</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.Morsel.output">
<code>Morsel.output(attrs=None, header='Set-Cookie:')</code> </dt> <dd>
<p>Return a string representation of the Morsel, suitable to be sent as an HTTP header. By default, all the attributes are included, unless <em>attrs</em> is given, in which case it should be a list of attributes to use. <em>header</em> is by default <code>"Set-Cookie:"</code>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.Morsel.js_output">
<code>Morsel.js_output(attrs=None)</code> </dt> <dd>
<p>Return an embeddable JavaScript snippet, which, if run on a browser which supports JavaScript, will act the same as if the HTTP header was sent.</p> <p>The meaning for <em>attrs</em> is the same as in <a class="reference internal" href="#http.cookies.Morsel.output" title="http.cookies.Morsel.output"><code>output()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.Morsel.OutputString">
<code>Morsel.OutputString(attrs=None)</code> </dt> <dd>
<p>Return a string representing the Morsel, without any surrounding HTTP or JavaScript.</p> <p>The meaning for <em>attrs</em> is the same as in <a class="reference internal" href="#http.cookies.Morsel.output" title="http.cookies.Morsel.output"><code>output()</code></a>.</p> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.Morsel.update">
<code>Morsel.update(values)</code> </dt> <dd>
<p>Update the values in the Morsel dictionary with the values in the dictionary <em>values</em>. Raise an error if any of the keys in the <em>values</em> dict is not a valid <span class="target" id="index-6"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2109.html"><strong>RFC 2109</strong></a> attribute.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>an error is raised for invalid keys.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.Morsel.copy">
<code>Morsel.copy(value)</code> </dt> <dd>
<p>Return a shallow copy of the Morsel object.</p> <div class="versionchanged"> <p><span class="versionmodified changed">Changed in version 3.5: </span>return a Morsel object instead of a dict.</p> </div> </dd>
</dl> <dl class="py method"> <dt class="sig sig-object py" id="http.cookies.Morsel.setdefault">
<code>Morsel.setdefault(key, value=None)</code> </dt> <dd>
<p>Raise an error if key is not a valid <span class="target" id="index-7"></span><a class="rfc reference external" href="https://datatracker.ietf.org/doc/html/rfc2109.html"><strong>RFC 2109</strong></a> attribute, otherwise behave the same as <a class="reference internal" href="stdtypes#dict.setdefault" title="dict.setdefault"><code>dict.setdefault()</code></a>.</p> </dd>
</dl> </section> <section id="example"> <span id="cookie-example"></span><h2>Example</h2> <p>The following example demonstrates how to use the <a class="reference internal" href="#module-http.cookies" title="http.cookies: Support for HTTP state management (cookies)."><code>http.cookies</code></a> module.</p> <pre data-language="pycon3">&gt;&gt;&gt; from http import cookies
&gt;&gt;&gt; C = cookies.SimpleCookie()
&gt;&gt;&gt; C["fig"] = "newton"
&gt;&gt;&gt; C["sugar"] = "wafer"
&gt;&gt;&gt; print(C) # generate HTTP headers
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
&gt;&gt;&gt; print(C.output()) # same thing
Set-Cookie: fig=newton
Set-Cookie: sugar=wafer
&gt;&gt;&gt; C = cookies.SimpleCookie()
&gt;&gt;&gt; C["rocky"] = "road"
&gt;&gt;&gt; C["rocky"]["path"] = "/cookie"
&gt;&gt;&gt; print(C.output(header="Cookie:"))
Cookie: rocky=road; Path=/cookie
&gt;&gt;&gt; print(C.output(attrs=[], header="Cookie:"))
Cookie: rocky=road
&gt;&gt;&gt; C = cookies.SimpleCookie()
&gt;&gt;&gt; C.load("chips=ahoy; vienna=finger") # load from a string (HTTP header)
&gt;&gt;&gt; print(C)
Set-Cookie: chips=ahoy
Set-Cookie: vienna=finger
&gt;&gt;&gt; C = cookies.SimpleCookie()
&gt;&gt;&gt; C.load('keebler="E=everybody; L=\\"Loves\\"; fudge=\\012;";')
&gt;&gt;&gt; print(C)
Set-Cookie: keebler="E=everybody; L=\"Loves\"; fudge=\012;"
&gt;&gt;&gt; C = cookies.SimpleCookie()
&gt;&gt;&gt; C["oreo"] = "doublestuff"
&gt;&gt;&gt; C["oreo"]["path"] = "/"
&gt;&gt;&gt; print(C)
Set-Cookie: oreo=doublestuff; Path=/
&gt;&gt;&gt; C = cookies.SimpleCookie()
&gt;&gt;&gt; C["twix"] = "none for you"
&gt;&gt;&gt; C["twix"].value
'none for you'
&gt;&gt;&gt; C = cookies.SimpleCookie()
&gt;&gt;&gt; C["number"] = 7 # equivalent to C["number"] = str(7)
&gt;&gt;&gt; C["string"] = "seven"
&gt;&gt;&gt; C["number"].value
'7'
&gt;&gt;&gt; C["string"].value
'seven'
&gt;&gt;&gt; print(C)
Set-Cookie: number=7
Set-Cookie: string=seven
</pre> </section> <div class="_attribution">
  <p class="_attribution-p">
    &copy; 2001&ndash;2023 Python Software Foundation<br>Licensed under the PSF License.<br>
    <a href="https://docs.python.org/3.12/library/http.cookies.html" class="_attribution-link">https://docs.python.org/3.12/library/http.cookies.html</a>
  </p>
</div>