rest25/library/cookielib.rst => rest262/library/cookielib.rst
n1- 
2:mod:`cookielib` --- Cookie handling for HTTP clients
3=====================================================
4
5.. module:: cookielib
n5+   :synopsis: Classes for automatic handling of HTTP cookies.
6.. moduleauthor:: John J. Lee <jjl@pobox.com>
7.. sectionauthor:: John J. Lee <jjl@pobox.com>
n8+ 
9+.. note::
10+   The :mod:`cookielib` module has been renamed to :mod:`http.cookiejar` in
11+   Python 3.0.  The :term:`2to3` tool will automatically adapt imports when
12+   converting your sources to 3.0.
8
9
10.. versionadded:: 2.4
11
12
13
14The :mod:`cookielib` module defines classes for automatic handling of HTTP
15cookies.  It is useful for accessing web sites that require small pieces of data
27introduced with RFC 2965.
28
29.. note::
30
31   The various named parameters found in :mailheader:`Set-Cookie` and
32   :mailheader:`Set-Cookie2` headers (eg. ``domain`` and ``expires``) are
33   conventionally referred to as :dfn:`attributes`.  To distinguish them from
34   Python attributes, the documentation for this module uses the term
n35-   :dfn:`cookie-attribute` instead
n40+   :dfn:`cookie-attribute` instead.
36
n37-.
38
39The module defines the following exception:
40
41
42.. exception:: LoadError
43
44   Instances of :class:`FileCookieJar` raise this exception on failure to load
45   cookies from a file.
46
47   .. note::
48
49      For backwards-compatibility with Python 2.4 (which raised an :exc:`IOError`),
n50-      :exc:`LoadError` is a subclass of :exc:`IOError`
n54+      :exc:`LoadError` is a subclass of :exc:`IOError`.
51
n52-   .
53
54The following classes are provided:
55
56
57.. class:: CookieJar(policy=None)
58
59   *policy* is an object implementing the :class:`CookiePolicy` interface.
60
90   other arguments, see the documentation for :class:`CookiePolicy` and
91   :class:`DefaultCookiePolicy` objects.
92
93   :class:`DefaultCookiePolicy` implements the standard accept / reject rules for
94   Netscape and RFC 2965 cookies.  By default, RFC 2109 cookies (ie. cookies
95   received in a :mailheader:`Set-Cookie` header with a version cookie-attribute of
96   1) are treated according to the RFC 2965 rules.  However, if RFC 2965 handling
97   is turned off or :attr:`rfc2109_as_netscape` is True, RFC 2109 cookies are
n98-   'downgraded' by the :class:`CookieJar` instance to Netscape cookies, by setting
n101+   'downgraded' by the :class:`CookieJar` instance to Netscape cookies, by
99-   the :attr:`version` attribute of the :class:`Cookie` instance to 0.
102+   setting the :attr:`version` attribute of the :class:`Cookie` instance to 0.
100-   :class:`DefaultCookiePolicy` also provides some parameters to allow some fine-
103+   :class:`DefaultCookiePolicy` also provides some parameters to allow some
101-   tuning of policy.
104+   fine-tuning of policy.
102
103
104.. class:: Cookie()
105
106   This class represents Netscape, RFC 2109 and RFC 2965 cookies.  It is not
107   expected that users of :mod:`cookielib` construct their own :class:`Cookie`
108   instances.  Instead, if necessary, call :meth:`make_cookies` on a
109   :class:`CookieJar` instance.
117   Module :mod:`Cookie`
118      HTTP cookie classes, principally useful for server-side code.  The
119      :mod:`cookielib` and :mod:`Cookie` modules do not depend on each other.
120
121   http://wwwsearch.sf.net/ClientCookie/
122      Extensions to this module, including a class for reading Microsoft Internet
123      Explorer cookies on Windows.
124
n125-   http://www.netscape.com/newsref/std/cookie_spec.html
n128+   http://wp.netscape.com/newsref/std/cookie_spec.html
126      The specification of the original Netscape cookie protocol.  Though this is
127      still the dominant protocol, the 'Netscape cookie protocol' implemented by all
128      the major browsers (and :mod:`cookielib`) only bears a passing resemblance to
129      the one sketched out in ``cookie_spec.html``.
130
131   :rfc:`2109` - HTTP State Management Mechanism
132      Obsoleted by RFC 2965. Uses :mailheader:`Set-Cookie` with version=1.
133
140
141   :rfc:`2964` - Use of HTTP State Management
142
143.. _cookie-jar-objects:
144
145CookieJar and FileCookieJar Objects
146-----------------------------------
147
n148-:class:`CookieJar` objects support the iterator protocol for iterating over
n151+:class:`CookieJar` objects support the :term:`iterator` protocol for iterating over
149contained :class:`Cookie` objects.
150
151:class:`CookieJar` has the following methods:
152
153
154.. method:: CookieJar.add_cookie_header(request)
155
156   Add correct :mailheader:`Cookie` header to *request*.
282   Clear all cookies and reload cookies from a saved file.
283
284   :meth:`revert` can raise the same exceptions as :meth:`load`. If there is a
285   failure, the object's state will not be altered.
286
287:class:`FileCookieJar` instances have the following public attributes:
288
289
n290-.. attribute:: XXX Class.filename
n293+.. attribute:: FileCookieJar.filename
291
292   Filename of default file in which to keep cookies.  This attribute may be
293   assigned to.
294
295
n296-.. attribute:: XXX Class.delayload
n299+.. attribute:: FileCookieJar.delayload
297
298   If true, load cookies lazily from disk.  This attribute should not be assigned
299   to.  This is only a hint, since this only affects performance, not behaviour
300   (unless the cookies on disk are changing). A :class:`CookieJar` object may
301   ignore it.  None of the :class:`FileCookieJar` classes included in the standard
302   library lazily loads cookies.
303
304
305.. _file-cookie-jar-classes:
306
307FileCookieJar subclasses and co-operation with web browsers
308-----------------------------------------------------------
309
310The following :class:`CookieJar` subclasses are provided for reading and writing
311.  Further :class:`CookieJar` subclasses, including one that reads Microsoft
312Internet Explorer cookies, are available at
n313-`<http://wwwsearch.sf.net/ClientCookie/>`_.
n316+http://wwwsearch.sf.net/ClientCookie/.
314
315
316.. class:: MozillaCookieJar(filename, delayload=None, policy=None)
317
318   A :class:`FileCookieJar` that can load from and save cookies to disk in the
319   Mozilla ``cookies.txt`` file format (which is also used by the Lynx and Netscape
320   browsers).
321
322   .. note::
323
n327+      Version 3 of the Firefox web browser no longer writes cookies in the
328+      ``cookies.txt`` file format.
329+ 
330+   .. note::
331+ 
324-      This loses information about RFC 2965 cookies, and also about newer or non-
332+      This loses information about RFC 2965 cookies, and also about newer or
325-      standard cookie-attributes such as ``port``.
333+      non-standard cookie-attributes such as ``port``.
326
327   .. warning::
328
329      Back up your cookies before saving if you have cookies whose loss / corruption
330      would be inconvenient (there are some subtleties which may lead to slight
331      changes in the file over a load / save round-trip).
332
333   Also note that cookies saved while Mozilla is running will get clobbered by
399   See the documentation for :meth:`domain_return_ok`.
400
401In addition to implementing the methods above, implementations of the
402:class:`CookiePolicy` interface must also supply the following attributes,
403indicating which protocols should be used, and how.  All of these attributes may
404be assigned to.
405
406
n407-.. attribute:: XXX Class.netscape
n415+.. attribute:: CookiePolicy.netscape
408
409   Implement Netscape protocol.
410
411
n412-.. attribute:: XXX Class.rfc2965
n420+.. attribute:: CookiePolicy.rfc2965
413
414   Implement RFC 2965 protocol.
415
416
n417-.. attribute:: XXX Class.hide_cookie2
n425+.. attribute:: CookiePolicy.hide_cookie2
418
419   Don't add :mailheader:`Cookie2` header to requests (the presence of this header
420   indicates to the server that we understand RFC 2965 cookies).
421
422The most useful way to define a :class:`CookiePolicy` class is by subclassing
423from :class:`DefaultCookiePolicy` and overriding some or all of the methods
424above.  :class:`CookiePolicy` itself may be used as a 'null policy' to allow
425setting and receiving any and all cookies (this is unlikely to be useful).
504   Return whether *domain* is not on the whitelist for setting or receiving
505   cookies.
506
507:class:`DefaultCookiePolicy` instances have the following attributes, which are
508all initialised from the constructor arguments of the same name, and which may
509all be assigned to.
510
511
n512-.. attribute:: XXX Class.rfc2109_as_netscape
n520+.. attribute:: DefaultCookiePolicy.rfc2109_as_netscape
513
514   If true, request that the :class:`CookieJar` instance downgrade RFC 2109 cookies
515   (ie. cookies received in a :mailheader:`Set-Cookie` header with a version
516   cookie-attribute of 1) to Netscape cookies by setting the version attribute of
517   the :class:`Cookie` instance to 0.  The default value is :const:`None`, in which
518   case RFC 2109 cookies are downgraded if and only if RFC 2965 handling is turned
519   off.  Therefore, RFC 2109 cookies are downgraded by default.
520
521   .. versionadded:: 2.5
522
523General strictness switches:
524
525
n526-.. attribute:: XXX Class.strict_domain
n534+.. attribute:: DefaultCookiePolicy.strict_domain
527
528   Don't allow sites to set two-component domains with country-code top-level
529   domains like ``.co.uk``, ``.gov.uk``, ``.co.nz``.etc.  This is far from perfect
530   and isn't guaranteed to work!
531
532RFC 2965 protocol strictness switches:
533
534
n535-.. attribute:: XXX Class.strict_rfc2965_unverifiable
n543+.. attribute:: DefaultCookiePolicy.strict_rfc2965_unverifiable
536
537   Follow RFC 2965 rules on unverifiable transactions (usually, an unverifiable
538   transaction is one resulting from a redirect or a request for an image hosted on
539   another site).  If this is false, cookies are *never* blocked on the basis of
540   verifiability
541
542Netscape protocol strictness switches:
543
544
n545-.. attribute:: XXX Class.strict_ns_unverifiable
n553+.. attribute:: DefaultCookiePolicy.strict_ns_unverifiable
546
547   apply RFC 2965 rules on unverifiable transactions even to Netscape cookies
548
549
n550-.. attribute:: XXX Class.strict_ns_domain
n558+.. attribute:: DefaultCookiePolicy.strict_ns_domain
551
552   Flags indicating how strict to be with domain-matching rules for Netscape
553   cookies.  See below for acceptable values.
554
555
n556-.. attribute:: XXX Class.strict_ns_set_initial_dollar
n564+.. attribute:: DefaultCookiePolicy.strict_ns_set_initial_dollar
557
558   Ignore cookies in Set-Cookie: headers that have names starting with ``'$'``.
559
560
n561-.. attribute:: XXX Class.strict_ns_set_path
n569+.. attribute:: DefaultCookiePolicy.strict_ns_set_path
562
563   Don't allow setting cookies whose path doesn't path-match request URI.
564
565:attr:`strict_ns_domain` is a collection of flags.  Its value is constructed by
566or-ing together (for example, ``DomainStrictNoDots|DomainStrictNonDomain`` means
567both flags are set).
568
569
n570-.. attribute:: XXX Class.DomainStrictNoDots
n578+.. attribute:: DefaultCookiePolicy.DomainStrictNoDots
571
572   When setting cookies, the 'host prefix' must not contain a dot (eg.
573   ``www.foo.bar.com`` can't set a cookie for ``.bar.com``, because ``www.foo``
574   contains a dot).
575
576
n577-.. attribute:: XXX Class.DomainStrictNonDomain
n585+.. attribute:: DefaultCookiePolicy.DomainStrictNonDomain
578
579   Cookies that did not explicitly specify a ``domain`` cookie-attribute can only
580   be returned to a domain equal to the domain that set the cookie (eg.
581   ``spam.example.com`` won't be returned cookies from ``example.com`` that had no
582   ``domain`` cookie-attribute).
583
584
n585-.. attribute:: XXX Class.DomainRFC2965Match
n593+.. attribute:: DefaultCookiePolicy.DomainRFC2965Match
586
587   When setting cookies, require a full RFC 2965 domain-match.
588
589The following attributes are provided for convenience, and are the most useful
590combinations of the above flags:
591
592
n593-.. attribute:: XXX Class.DomainLiberal
n601+.. attribute:: DefaultCookiePolicy.DomainLiberal
594
595   Equivalent to 0 (ie. all of the above Netscape domain strictness flags switched
596   off).
597
598
n599-.. attribute:: XXX Class.DomainStrict
n607+.. attribute:: DefaultCookiePolicy.DomainStrict
600
601   Equivalent to ``DomainStrictNoDots|DomainStrictNonDomain``.
602
603
n604-.. _cookie-objects:
n612+.. _cookielib-cookie-objects:
605
606Cookie Objects
607--------------
608
609:class:`Cookie` instances have Python attributes roughly corresponding to the
610standard cookie-attributes specified in the various cookie standards.  The
611correspondence is not one-to-one, because there are complicated rules for
n612-assigning default values, because the ``max-age`` and ``expires`` cookie-
n620+assigning default values, because the ``max-age`` and ``expires``
613-attributes contain equivalent information, and because RFC 2109 cookies may be
621+cookie-attributes contain equivalent information, and because RFC 2109 cookies
614-'downgraded' by :mod:`cookielib` from version 1 to version 0 (Netscape) cookies.
622+may be 'downgraded' by :mod:`cookielib` from version 1 to version 0 (Netscape)
623+cookies.
615
616Assignment to these attributes should not be necessary other than in rare
617circumstances in a :class:`CookiePolicy` method.  The class does not enforce
618internal consistency, so you should know what you're doing if you do that.
619
620
621.. attribute:: Cookie.version
622
672.. attribute:: Cookie.comment_url
673
674   URL linking to a comment from the server explaining the function of this cookie,
675   or :const:`None`.
676
677
678.. attribute:: Cookie.rfc2109
679
n680-   True if this cookie was received as an RFC 2109 cookie (ie. the cookie arrived
n689+   True if this cookie was received as an RFC 2109 cookie (ie. the cookie
681-   in a :mailheader:`Set-Cookie` header, and the value of the Version cookie-
690+   arrived in a :mailheader:`Set-Cookie` header, and the value of the Version
682-   attribute in that header was 1).  This attribute is provided because
691+   cookie-attribute in that header was 1).  This attribute is provided because
683-   :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which
692+   :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in
684-   case :attr:`version` is 0.
693+   which case :attr:`version` is 0.
685
686   .. versionadded:: 2.5
687
688
689.. attribute:: Cookie.port_specified
690
691   True if a port or set of ports was explicitly specified by the server (in the
692   :mailheader:`Set-Cookie` / :mailheader:`Set-Cookie2` header).
719
720.. method:: Cookie.set_nonstandard_attr(name, value)
721
722   Set the value of the named cookie-attribute.
723
724The :class:`Cookie` class also defines the following method:
725
726
n727-.. method:: Cookie.is_expired([now=:const:`None`])
n736+.. method:: Cookie.is_expired([now=None])
728
729   True if cookie has passed the time at which the server requested it should
730   expire.  If *now* is given (in seconds since the epoch), return whether the
731   cookie has expired at the specified time.
732
733
734.. _cookielib-examples:
735
755The next example illustrates the use of :class:`DefaultCookiePolicy`. Turn on
756RFC 2965 cookies, be more strict about domains when setting and returning
757Netscape cookies, and block some domains from setting cookies or having them
758returned::
759
760   import urllib2
761   from cookielib import CookieJar, DefaultCookiePolicy
762   policy = DefaultCookiePolicy(
t763-       rfc2965=True, strict_ns_domain=Policy.DomainStrict,
t772+       rfc2965=True, strict_ns_domain=DefaultCookiePolicy.DomainStrict,
764       blocked_domains=["ads.net", ".ads.net"])
765   cj = CookieJar(policy)
766   opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
767   r = opener.open("http://example.com/")
768
Legends
Colors
 Added 
Changed
Deleted
Links
(f)irst change
(n)ext change
(t)op