[code.view]

[top] / python / PyMOTW / docs / Cookie / index.html


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    
    <title>Cookie – HTTP Cookies &mdash; Python Module of the Week</title>
    <link rel="stylesheet" href="../_static/sphinxdoc.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript">
      var DOCUMENTATION_OPTIONS = {
        URL_ROOT:    '../',
        VERSION:     '1.132',
        COLLAPSE_INDEX: false,
        FILE_SUFFIX: '.html',
        HAS_SOURCE:  true
      };
    </script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <link rel="author" title="About these documents" href="../about.html" />
    <link rel="top" title="Python Module of the Week" href="../index.html" />
    <link rel="up" title="Internet Protocols and Support" href="../internet_protocols.html" />
    <link rel="next" title="imaplib - IMAP4 client library" href="../imaplib/index.html" />
    <link rel="prev" title="cgitb – Detailed traceback reports" href="../cgitb/index.html" /> 
  </head>
  <body>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             accesskey="I">index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../imaplib/index.html" title="imaplib - IMAP4 client library"
             accesskey="N">next</a> |</li>
        <li class="right" >
          <a href="../cgitb/index.html" title="cgitb – Detailed traceback reports"
             accesskey="P">previous</a> |</li>
        <li><a href="../contents.html">PyMOTW</a> &raquo;</li>
          <li><a href="../internet_protocols.html" accesskey="U">Internet Protocols and Support</a> &raquo;</li> 
      </ul>
    </div>
      <div class="sphinxsidebar">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table Of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">Cookie &#8211; HTTP Cookies</a><ul>
<li><a class="reference internal" href="#creating-and-setting-a-cookie">Creating and Setting a Cookie</a></li>
<li><a class="reference internal" href="#morsels">Morsels</a></li>
<li><a class="reference internal" href="#encoded-values">Encoded Values</a></li>
<li><a class="reference internal" href="#receiving-and-parsing-cookie-headers">Receiving and Parsing Cookie Headers</a></li>
<li><a class="reference internal" href="#alternative-output-formats">Alternative Output Formats</a></li>
<li><a class="reference internal" href="#deprecated-classes">Deprecated Classes</a></li>
</ul>
</li>
</ul>

  <h4>Previous topic</h4>
  <p class="topless"><a href="../cgitb/index.html"
                        title="previous chapter">cgitb &#8211; Detailed traceback reports</a></p>
  <h4>Next topic</h4>
  <p class="topless"><a href="../imaplib/index.html"
                        title="next chapter">imaplib - IMAP4 client library</a></p>
  <h3>This Page</h3>
  <ul class="this-page-menu">
    <li><a href="../_sources/Cookie/index.txt"
           rel="nofollow">Show Source</a></li>
  </ul>
<div id="searchbox" style="display: none">
  <h3>Quick search</h3>
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" size="18" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    <p class="searchtip" style="font-size: 90%">
    Enter search terms or a module, class or function name.
    </p>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>

    <div class="document">
      <div class="documentwrapper">
        <div class="bodywrapper">
          <div class="body">
            
  <div class="section" id="module-Cookie">
<span id="cookie-http-cookies"></span><h1>Cookie &#8211; HTTP Cookies<a class="headerlink" href="#module-Cookie" title="Permalink to this headline">¶</a></h1>
<table class="docutils field-list" frame="void" rules="none">
<col class="field-name" />
<col class="field-body" />
<tbody valign="top">
<tr class="field"><th class="field-name">Purpose:</th><td class="field-body">The Cookie module defines classes for parsing and creating HTTP cookie headers.</td>
</tr>
<tr class="field"><th class="field-name">Python Version:</th><td class="field-body">2.1 and later</td>
</tr>
</tbody>
</table>
<p>Cookies have been a part of the HTTP protocol for a long time. All of the
modern web development frameworks provide easy access to cookies so a
programmer almost never has to worry about how to format them or make sure the
headers are sent properly. It can be instructive to understand how cookies
work, though, and the options they support.</p>
<p>The Cookie module implements a parser for cookies that is mostly <span class="target" id="index-0"></span><a class="rfc reference external" href="http://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a>
compliant. It is a little less strict than the standard because MSIE 3.0x does
not support the entire standard.</p>
<div class="section" id="creating-and-setting-a-cookie">
<h2>Creating and Setting a Cookie<a class="headerlink" href="#creating-and-setting-a-cookie" title="Permalink to this headline">¶</a></h2>
<p>Cookies are used as state management, and as such as usually set by the server
to be stored and returned by the client. The most trivial example of creating
a cookie looks something like:</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">Cookie</span>

<span class="n">c</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;mycookie&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;cookie_value&#39;</span>
<span class="k">print</span> <span class="n">c</span>
</pre></div>
</div>
<p>The output is a valid Set-Cookie header ready to be passed to the client as
part of the HTTP response:</p>
<div class="highlight-python"><pre>$ python Cookie_setheaders.py

Set-Cookie: mycookie=cookie_value</pre>
</div>
</div>
<div class="section" id="morsels">
<h2>Morsels<a class="headerlink" href="#morsels" title="Permalink to this headline">¶</a></h2>
<p>It is also possible to control the other aspects of a cookie, such as the
expiration, path, and domain. In fact, all of the RFC attributes for cookies
can be managed through the Morsel object representing the cookie value.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">Cookie</span>
<span class="kn">import</span> <span class="nn">datetime</span>

<span class="k">def</span> <span class="nf">show_cookie</span><span class="p">(</span><span class="n">c</span><span class="p">):</span>
    <span class="k">print</span> <span class="n">c</span>
    <span class="k">for</span> <span class="n">key</span><span class="p">,</span> <span class="n">morsel</span> <span class="ow">in</span> <span class="n">c</span><span class="o">.</span><span class="n">iteritems</span><span class="p">():</span>
        <span class="k">print</span>
        <span class="k">print</span> <span class="s">&#39;key =&#39;</span><span class="p">,</span> <span class="n">morsel</span><span class="o">.</span><span class="n">key</span>
        <span class="k">print</span> <span class="s">&#39;  value =&#39;</span><span class="p">,</span> <span class="n">morsel</span><span class="o">.</span><span class="n">value</span>
        <span class="k">print</span> <span class="s">&#39;  coded_value =&#39;</span><span class="p">,</span> <span class="n">morsel</span><span class="o">.</span><span class="n">coded_value</span>
        <span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="n">morsel</span><span class="o">.</span><span class="n">keys</span><span class="p">():</span>
            <span class="k">if</span> <span class="n">morsel</span><span class="p">[</span><span class="n">name</span><span class="p">]:</span>
                <span class="k">print</span> <span class="s">&#39;  </span><span class="si">%s</span><span class="s"> = </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="p">(</span><span class="n">name</span><span class="p">,</span> <span class="n">morsel</span><span class="p">[</span><span class="n">name</span><span class="p">])</span>

<span class="n">c</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>

<span class="c"># A cookie with a value that has to be encoded to fit into the header</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;encoded_value_cookie&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;&quot;cookie_value&quot;&#39;</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;encoded_value_cookie&#39;</span><span class="p">][</span><span class="s">&#39;comment&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;Notice that this cookie value has escaped quotes&#39;</span>

<span class="c"># A cookie that only applies to part of a site</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;restricted_cookie&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;cookie_value&#39;</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;restricted_cookie&#39;</span><span class="p">][</span><span class="s">&#39;path&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;/sub/path&#39;</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;restricted_cookie&#39;</span><span class="p">][</span><span class="s">&#39;domain&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;PyMOTW&#39;</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;restricted_cookie&#39;</span><span class="p">][</span><span class="s">&#39;secure&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="bp">True</span>

<span class="c"># A cookie that expires in 5 minutes</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;with_max_age&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;expires in 5 minutes&#39;</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;with_max_age&#39;</span><span class="p">][</span><span class="s">&#39;max-age&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">300</span> <span class="c"># seconds</span>

<span class="c"># A cookie that expires at a specific time</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;expires_at_time&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;cookie_value&#39;</span>
<span class="n">expires</span> <span class="o">=</span> <span class="n">datetime</span><span class="o">.</span><span class="n">datetime</span><span class="p">(</span><span class="mi">2009</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">14</span><span class="p">,</span> <span class="mi">18</span><span class="p">,</span> <span class="mi">30</span><span class="p">,</span> <span class="mi">14</span><span class="p">)</span> <span class="o">+</span> <span class="n">datetime</span><span class="o">.</span><span class="n">timedelta</span><span class="p">(</span><span class="n">hours</span><span class="o">=</span><span class="mi">1</span><span class="p">)</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;expires_at_time&#39;</span><span class="p">][</span><span class="s">&#39;expires&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="n">expires</span><span class="o">.</span><span class="n">strftime</span><span class="p">(</span><span class="s">&#39;%a, </span><span class="si">%d</span><span class="s"> %b %Y %H:%M:%S&#39;</span><span class="p">)</span> <span class="c"># Wdy, DD-Mon-YY HH:MM:SS GMT</span>

<span class="n">show_cookie</span><span class="p">(</span><span class="n">c</span><span class="p">)</span>
</pre></div>
</div>
<p>The above example includes two different methods for setting stored cookies
that expire. You can set max-age to a number of seconds, or expires to a date
and time when the cookie should be discarded.</p>
<div class="highlight-python"><pre>$ python Cookie_Morsel.py

Set-Cookie: encoded_value_cookie="\"cookie_value\""; Comment=Notice that this cookie value has escaped quotes
Set-Cookie: expires_at_time=cookie_value; expires=Sat, 14 Feb 2009 19:30:14
Set-Cookie: restricted_cookie=cookie_value; Domain=PyMOTW; Path=/sub/path; secure
Set-Cookie: with_max_age="expires in 5 minutes"; Max-Age=300

key = restricted_cookie
  value = cookie_value
  coded_value = cookie_value
  domain = PyMOTW
  secure = True
  path = /sub/path

key = with_max_age
  value = expires in 5 minutes
  coded_value = "expires in 5 minutes"
  max-age = 300

key = encoded_value_cookie
  value = "cookie_value"
  coded_value = "\"cookie_value\""
  comment = Notice that this cookie value has escaped quotes

key = expires_at_time
  value = cookie_value
  coded_value = cookie_value
  expires = Sat, 14 Feb 2009 19:30:14</pre>
</div>
<p>Both the Cookie and Morsel objects act like dictionaries. The Morsel responds
to a fixed set of keys:</p>
<ul class="simple">
<li>expires</li>
<li>path</li>
<li>comment</li>
<li>domain</li>
<li>max-age</li>
<li>secure</li>
<li>version</li>
</ul>
<p>The keys for the Cookie instance are the names of the individual cookies being
stored. That information is also available from the key attribute of the
Morsel.</p>
</div>
<div class="section" id="encoded-values">
<h2>Encoded Values<a class="headerlink" href="#encoded-values" title="Permalink to this headline">¶</a></h2>
<p>The cookie header may require values to be encoded so they can be parsed
properly.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">Cookie</span>

<span class="n">c</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;integer&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="mi">5</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;string_with_quotes&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;He said, &quot;Hello, World!&quot;&#39;</span>

<span class="k">for</span> <span class="n">name</span> <span class="ow">in</span> <span class="p">[</span><span class="s">&#39;integer&#39;</span><span class="p">,</span> <span class="s">&#39;string_with_quotes&#39;</span><span class="p">]:</span>
    <span class="k">print</span> <span class="n">c</span><span class="p">[</span><span class="n">name</span><span class="p">]</span><span class="o">.</span><span class="n">key</span>
    <span class="k">print</span> <span class="s">&#39;  </span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">c</span><span class="p">[</span><span class="n">name</span><span class="p">]</span>
    <span class="k">print</span> <span class="s">&#39;  value=</span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">c</span><span class="p">[</span><span class="n">name</span><span class="p">]</span><span class="o">.</span><span class="n">value</span><span class="p">,</span> <span class="nb">type</span><span class="p">(</span><span class="n">c</span><span class="p">[</span><span class="n">name</span><span class="p">]</span><span class="o">.</span><span class="n">value</span><span class="p">)</span>
    <span class="k">print</span> <span class="s">&#39;  coded_value=</span><span class="si">%s</span><span class="s">&#39;</span> <span class="o">%</span> <span class="n">c</span><span class="p">[</span><span class="n">name</span><span class="p">]</span><span class="o">.</span><span class="n">coded_value</span>
    <span class="k">print</span>
</pre></div>
</div>
<p>The Morsel.value is always the decoded value of the cookie, while
Morsel.coded_value is always the representation to be used for transmitting
the value to the client. Both values are always strings. Values saved to a
cookie that are not strings are converted automatically.</p>
<div class="highlight-python"><pre>$ python Cookie_coded_value.py

integer
  Set-Cookie: integer=5
  value=5 &lt;type 'str'&gt;
  coded_value=5

string_with_quotes
  Set-Cookie: string_with_quotes="He said, \"Hello, World!\""
  value=He said, "Hello, World!" &lt;type 'str'&gt;
  coded_value="He said, \"Hello, World!\""</pre>
</div>
</div>
<div class="section" id="receiving-and-parsing-cookie-headers">
<h2>Receiving and Parsing Cookie Headers<a class="headerlink" href="#receiving-and-parsing-cookie-headers" title="Permalink to this headline">¶</a></h2>
<p>Once the Set-Cookie headers are received by the client, it will return those
cookies to the server on subsequent requests using the Cookie header. The
incoming header will look like:</p>
<div class="highlight-python"><pre>Cookie: integer=5; string_with_quotes="He said, \"Hello, World!\""</pre>
</div>
<p>Depending on your web server and framework, the cookies are either
available directly from the headers or the <tt class="docutils literal"><span class="pre">HTTP_COOKIE</span></tt> environment
variable. To decode them, pass the string without the header prefix to
the SimpleCookie when instantiating it, or use the load() method.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">Cookie</span>

<span class="n">HTTP_COOKIE</span> <span class="o">=</span> <span class="s">r&#39;integer=5; string_with_quotes=&quot;He said, \&quot;Hello, World!\&quot;&quot;&#39;</span>

<span class="k">print</span> <span class="s">&#39;From constructor:&#39;</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">(</span><span class="n">HTTP_COOKIE</span><span class="p">)</span>
<span class="k">print</span> <span class="n">c</span>

<span class="k">print</span>
<span class="k">print</span> <span class="s">&#39;From load():&#39;</span>
<span class="n">c</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>
<span class="n">c</span><span class="o">.</span><span class="n">load</span><span class="p">(</span><span class="n">HTTP_COOKIE</span><span class="p">)</span>
<span class="k">print</span> <span class="n">c</span>
</pre></div>
</div>
<div class="highlight-python"><pre>$ python Cookie_parse.py

From constructor:
Set-Cookie: integer=5
Set-Cookie: string_with_quotes="He said, \"Hello, World!\""

From load():
Set-Cookie: integer=5
Set-Cookie: string_with_quotes="He said, \"Hello, World!\""</pre>
</div>
</div>
<div class="section" id="alternative-output-formats">
<h2>Alternative Output Formats<a class="headerlink" href="#alternative-output-formats" title="Permalink to this headline">¶</a></h2>
<p>Besides using the Set-Cookie header, it is possible to use JavaScript to add
cookies to a client. SimpleCookie and Morsel provide JavaScript output via the
js_output() method.</p>
<div class="highlight-python"><div class="highlight"><pre><span class="kn">import</span> <span class="nn">Cookie</span>

<span class="n">c</span> <span class="o">=</span> <span class="n">Cookie</span><span class="o">.</span><span class="n">SimpleCookie</span><span class="p">()</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;mycookie&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;cookie_value&#39;</span>
<span class="n">c</span><span class="p">[</span><span class="s">&#39;another_cookie&#39;</span><span class="p">]</span> <span class="o">=</span> <span class="s">&#39;second value&#39;</span>
<span class="k">print</span> <span class="n">c</span><span class="o">.</span><span class="n">js_output</span><span class="p">()</span>
</pre></div>
</div>
<div class="highlight-python"><pre>$ python Cookie_js_output.py


        &lt;script type="text/javascript"&gt;
        &lt;!-- begin hiding
        document.cookie = "another_cookie=\"second value\"";
        // end hiding --&gt;
        &lt;/script&gt;

        &lt;script type="text/javascript"&gt;
        &lt;!-- begin hiding
        document.cookie = "mycookie=cookie_value";
        // end hiding --&gt;
        &lt;/script&gt;</pre>
</div>
</div>
<div class="section" id="deprecated-classes">
<h2>Deprecated Classes<a class="headerlink" href="#deprecated-classes" title="Permalink to this headline">¶</a></h2>
<p>All of these examples have used SimpleCookie. The Cookie module also provides
2 other classes, SerialCookie and SmartCookie. SerialCookie can handle any
values that can be pickled. SmartCookie figures out whether a value needs to
be unpickled or if it is a simple value. Since both of these classes use
pickles, they are potential security holes in your application and you should
not use them. It is safer to store state on the server, and give the client a
session key instead.</p>
<div class="admonition-see-also admonition seealso">
<p class="first admonition-title">See also</p>
<dl class="last docutils">
<dt><a class="reference external" href="http://docs.python.org/library/cookie.html">Cookie</a></dt>
<dd>The standard library documentation for this module.</dd>
<dt><tt class="xref py py-mod docutils literal"><span class="pre">cookielib</span></tt></dt>
<dd>The <tt class="xref py py-mod docutils literal"><span class="pre">cookielib</span></tt> module, for working with cookies on the client-side.</dd>
<dt><span class="target" id="index-1"></span><a class="rfc reference external" href="http://tools.ietf.org/html/rfc2109.html"><strong>RFC 2109</strong></a></dt>
<dd>HTTP State Management Mechanism</dd>
</dl>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      <div class="clearer"></div>
    </div>
    <div class="related">
      <h3>Navigation</h3>
      <ul>
        <li class="right" style="margin-right: 10px">
          <a href="../genindex.html" title="General Index"
             >index</a></li>
        <li class="right" >
          <a href="../py-modindex.html" title="Python Module Index"
             >modules</a> |</li>
        <li class="right" >
          <a href="../imaplib/index.html" title="imaplib - IMAP4 client library"
             >next</a> |</li>
        <li class="right" >
          <a href="../cgitb/index.html" title="cgitb – Detailed traceback reports"
             >previous</a> |</li>
        <li><a href="../contents.html">PyMOTW</a> &raquo;</li>
          <li><a href="../internet_protocols.html" >Internet Protocols and Support</a> &raquo;</li> 
      </ul>
    </div>
    <div class="footer">
      &copy; Copyright Doug Hellmann.
      Last updated on Oct 24, 2010.
      Created using <a href="http://sphinx.pocoo.org/">Sphinx</a>.

    <br/><a href="http://creativecommons.org/licenses/by-nc-sa/3.0/us/" rel="license"><img alt="Creative Commons License" style="border-width:0" src="http://i.creativecommons.org/l/by-nc-sa/3.0/us/88x31.png"/></a>
    
    </div>
  </body>
</html>

[top] / python / PyMOTW / docs / Cookie / index.html

contact | logmethods.com