720 lines · 28.1 KB · TeX
RawDownload
\section{\module{cookielib} ---         Cookie handling for HTTP clients} \declaremodule{standard}{cookielib}\moduleauthor{John J. Lee}{jjl@pobox.com}\sectionauthor{John J. Lee}{jjl@pobox.com} \versionadded{2.4} \modulesynopsis{Cookie handling for HTTP clients} The \module{cookielib} module defines classes for automatic handlingof HTTP cookies.  It is useful for accessing web sites that requiresmall pieces of data -- \dfn{cookies} -- to be set on the clientmachine by an HTTP response from a web server, and then returned tothe server in later HTTP requests. Both the regular Netscape cookie protocol and the protocol defined by\rfc{2965} are handled.  RFC 2965 handling is switched off by default.\rfc{2109} cookies are parsed as Netscape cookies and subsequentlytreated either as Netscape or RFC 2965 cookies according to the'policy' in effect.  Note that the great majority of cookies on theInternet are Netscape cookies.  \module{cookielib} attempts to followthe de-facto Netscape cookie protocol (which differs substantiallyfrom that set out in the original Netscape specification), includingtaking note of the \code{max-age} and \code{port} cookie-attributesintroduced with RFC 2965.  \note{The various named parameters found in\mailheader{Set-Cookie} and \mailheader{Set-Cookie2} headers(eg. \code{domain} and \code{expires}) are conventionally referred toas \dfn{attributes}.  To distinguish them from Python attributes, thedocumentation for this module uses the term \dfn{cookie-attribute}instead}.  The module defines the following exception: \begin{excdesc}{LoadError}Instances of \class{FileCookieJar} raise this exception on failure toload cookies from a file.  \note{For backwards-compatibilitywith Python 2.4 (which raised an \exception{IOError}),\exception{LoadError} is a subclass of \exception{IOError}}.\end{excdesc}  The following classes are provided: \begin{classdesc}{CookieJar}{policy=\constant{None}}\var{policy} is an object implementing the \class{CookiePolicy}interface. The \class{CookieJar} class stores HTTP cookies.  It extracts cookiesfrom HTTP requests, and returns them in HTTP responses.\class{CookieJar} instances automatically expire contained cookieswhen necessary.  Subclasses are also responsible for storing andretrieving cookies from a file or database.\end{classdesc} \begin{classdesc}{FileCookieJar}{filename, delayload=\constant{None}, policy=\constant{None}}\var{policy} is an object implementing the \class{CookiePolicy}interface.  For the other arguments, see the documentation for thecorresponding attributes. A \class{CookieJar} which can load cookies from, and perhaps savecookies to, a file on disk.  Cookies are \strong{NOT} loaded from thenamed file until either the \method{load()} or \method{revert()}method is called.  Subclasses of this class are documented in section\ref{file-cookie-jar-classes}.\end{classdesc} \begin{classdesc}{CookiePolicy}{}This class is responsible for deciding whether each cookie should beaccepted from / returned to the server.\end{classdesc} \begin{classdesc}{DefaultCookiePolicy}{    blocked_domains=\constant{None},    allowed_domains=\constant{None},    netscape=\constant{True}, rfc2965=\constant{False},    rfc2109_as_netscape=\constant{None},    hide_cookie2=\constant{False},    strict_domain=\constant{False},    strict_rfc2965_unverifiable=\constant{True},    strict_ns_unverifiable=\constant{False},    strict_ns_domain=\constant{DefaultCookiePolicy.DomainLiberal},    strict_ns_set_initial_dollar=\constant{False},    strict_ns_set_path=\constant{False}  } Constructor arguments should be passed as keyword arguments only.\var{blocked_domains} is a sequence of domain names that we neveraccept cookies from, nor return cookies to. \var{allowed_domains} ifnot \constant{None}, this is a sequence of the only domains for whichwe accept and return cookies.  For all other arguments, see thedocumentation for \class{CookiePolicy} and \class{DefaultCookiePolicy}objects. \class{DefaultCookiePolicy} implements the standard accept / rejectrules for Netscape and RFC 2965 cookies.  By default, RFC 2109 cookies(ie. cookies received in a \mailheader{Set-Cookie} header with aversion cookie-attribute of 1) are treated according to the RFC 2965rules.  However, if RFC 2965 handling is turned off or\member{rfc2109_as_netscape} is True, RFC 2109 cookies are'downgraded' by the \class{CookieJar} instance to Netscape cookies, bysetting the \member{version} attribute of the \class{Cookie} instanceto 0.  \class{DefaultCookiePolicy} also provides some parameters toallow some fine-tuning of policy.\end{classdesc} \begin{classdesc}{Cookie}{}This class represents Netscape, RFC 2109 and RFC 2965 cookies.  It isnot expected that users of \module{cookielib} construct their own\class{Cookie} instances.  Instead, if necessary, call\method{make_cookies()} on a \class{CookieJar} instance.\end{classdesc} \begin{seealso} \seemodule{urllib2}{URL opening with automatic cookie handling.} \seemodule{Cookie}{HTTP cookie classes, principally useful forserver-side code.  The \module{cookielib} and \module{Cookie} modulesdo not depend on each other.} \seeurl{http://wwwsearch.sf.net/ClientCookie/}{Extensions to thismodule, including a class for reading Microsoft Internet Explorercookies on Windows.} \seeurl{http://www.netscape.com/newsref/std/cookie_spec.html}{Thespecification of the original Netscape cookie protocol.  Though thisis still the dominant protocol, the 'Netscape cookie protocol'implemented by all the major browsers (and \module{cookielib}) onlybears a passing resemblance to the one sketched out in\code{cookie_spec.html}.} \seerfc{2109}{HTTP State Management Mechanism}{Obsoleted by RFC 2965.Uses \mailheader{Set-Cookie} with version=1.} \seerfc{2965}{HTTP State Management Mechanism}{The Netscape protocolwith the bugs fixed.  Uses \mailheader{Set-Cookie2} in place of\mailheader{Set-Cookie}.  Not widely used.} \seeurl{http://kristol.org/cookie/errata.html}{Unfinished errata toRFC 2965.} \seerfc{2964}{Use of HTTP State Management}{} \end{seealso}  \subsection{CookieJar and FileCookieJar Objects \label{cookie-jar-objects}} \class{CookieJar} objects support the iterator protocol for iteratingover contained \class{Cookie} objects. \class{CookieJar} has the following methods: \begin{methoddesc}[CookieJar]{add_cookie_header}{request}Add correct \mailheader{Cookie} header to \var{request}. If policy allows (ie. the \member{rfc2965} and \member{hide_cookie2}attributes of the \class{CookieJar}'s \class{CookiePolicy} instanceare true and false respectively), the \mailheader{Cookie2} header isalso added when appropriate. The \var{request} object (usually a \class{urllib2.Request} instance)must support the methods \method{get_full_url()}, \method{get_host()},\method{get_type()}, \method{unverifiable()},\method{get_origin_req_host()}, \method{has_header()},\method{get_header()}, \method{header_items()}, and\method{add_unredirected_header()},as documented by \module{urllib2}.\end{methoddesc} \begin{methoddesc}[CookieJar]{extract_cookies}{response, request}Extract cookies from HTTP \var{response} and store them in the\class{CookieJar}, where allowed by policy. The \class{CookieJar} will look for allowable \mailheader{Set-Cookie}and \mailheader{Set-Cookie2} headers in the \var{response} argument,and store cookies as appropriate (subject to the\method{CookiePolicy.set_ok()} method's approval). The \var{response} object (usually the result of a call to\method{urllib2.urlopen()}, or similar) should support an\method{info()} method, which returns an object with a\method{getallmatchingheaders()} method (usually a\class{mimetools.Message} instance). The \var{request} object (usually a \class{urllib2.Request} instance)must support the methods \method{get_full_url()}, \method{get_host()},\method{unverifiable()}, and \method{get_origin_req_host()}, asdocumented by \module{urllib2}.  The request is used to set defaultvalues for cookie-attributes as well as for checking that the cookieis allowed to be set.\end{methoddesc} \begin{methoddesc}[CookieJar]{set_policy}{policy}Set the \class{CookiePolicy} instance to be used.\end{methoddesc} \begin{methoddesc}[CookieJar]{make_cookies}{response, request}Return sequence of \class{Cookie} objects extracted from\var{response} object. See the documentation for \method{extract_cookies} for the interfacesrequired of the \var{response} and \var{request} arguments.\end{methoddesc} \begin{methoddesc}[CookieJar]{set_cookie_if_ok}{cookie, request}Set a \class{Cookie} if policy says it's OK to do so.\end{methoddesc} \begin{methoddesc}[CookieJar]{set_cookie}{cookie}Set a \class{Cookie}, without checking with policy to see whether ornot it should be set.\end{methoddesc} \begin{methoddesc}[CookieJar]{clear}{\optional{domain\optional{,      path\optional{, name}}}}Clear some cookies. If invoked without arguments, clear all cookies.  If given a singleargument, only cookies belonging to that \var{domain} will be removed.If given two arguments, cookies belonging to the specified\var{domain} and URL \var{path} are removed.  If given threearguments, then the cookie with the specified \var{domain}, \var{path}and \var{name} is removed. Raises \exception{KeyError} if no matching cookie exists.\end{methoddesc} \begin{methoddesc}[CookieJar]{clear_session_cookies}{}Discard all session cookies. Discards all contained cookies that have a true \member{discard}attribute (usually because they had either no \code{max-age} or\code{expires} cookie-attribute, or an explicit \code{discard}cookie-attribute).  For interactive browsers, the end of a sessionusually corresponds to closing the browser window. Note that the \method{save()} method won't save session cookiesanyway, unless you ask otherwise by passing a true\var{ignore_discard} argument.\end{methoddesc} \class{FileCookieJar} implements the following additional methods: \begin{methoddesc}[FileCookieJar]{save}{filename=\constant{None},    ignore_discard=\constant{False}, ignore_expires=\constant{False}}Save cookies to a file. This base class raises \exception{NotImplementedError}.  Subclasses mayleave this method unimplemented. \var{filename} is the name of file in which to save cookies.  If\var{filename} is not specified, \member{self.filename} is used (whosedefault is the value passed to the constructor, if any); if\member{self.filename} is \constant{None}, \exception{ValueError} israised. \var{ignore_discard}: save even cookies set to be discarded.\var{ignore_expires}: save even cookies that have expired The file is overwritten if it already exists, thus wiping all thecookies it contains.  Saved cookies can be restored later using the\method{load()} or \method{revert()} methods.\end{methoddesc} \begin{methoddesc}[FileCookieJar]{load}{filename=\constant{None},    ignore_discard=\constant{False}, ignore_expires=\constant{False}}Load cookies from a file. Old cookies are kept unless overwritten by newly loaded ones. Arguments are as for \method{save()}. The named file must be in the format understood by the class, or\exception{LoadError} will be raised.  Also, \exception{IOError} maybe raised, for example if the file does not exist.  \note{Forbackwards-compatibility with Python 2.4 (which raisedan \exception{IOError}), \exception{LoadError} is a subclassof \exception{IOError}.}\end{methoddesc} \begin{methoddesc}[FileCookieJar]{revert}{filename=\constant{None},    ignore_discard=\constant{False}, ignore_expires=\constant{False}}Clear all cookies and reload cookies from a saved file. \method{revert()} can raise the same exceptions as \method{load()}.If there is a failure, the object's state will not be altered.\end{methoddesc} \class{FileCookieJar} instances have the following public attributes: \begin{memberdesc}{filename}Filename of default file in which to keep cookies.  This attribute maybe assigned to.\end{memberdesc} \begin{memberdesc}{delayload}If true, load cookies lazily from disk.  This attribute should not beassigned to.  This is only a hint, since this only affectsperformance, not behaviour (unless the cookies on disk are changing).A \class{CookieJar} object may ignore it.  None of the\class{FileCookieJar} classes included in the standard library lazilyloads cookies.\end{memberdesc}  \subsection{FileCookieJar subclasses and co-operation with web browsers  \label{file-cookie-jar-classes}} The following \class{CookieJar} subclasses are provided for readingand writing .  Further \class{CookieJar} subclasses, including onethat reads Microsoft Internet Explorer cookies, are available at\url{http://wwwsearch.sf.net/ClientCookie/}. \begin{classdesc}{MozillaCookieJar}{filename, delayload=\constant{None}, policy=\constant{None}}A \class{FileCookieJar} that can load from and save cookies to disk inthe Mozilla \code{cookies.txt} file format (which is also used by theLynx and Netscape browsers).  \note{This loses information about RFC2965 cookies, and also about newer or non-standard cookie-attributessuch as \code{port}.} \warning{Back up your cookies before saving if you have cookies whoseloss / corruption would be inconvenient (there are some subtletieswhich may lead to slight changes in the file over a load / saveround-trip).} Also note that cookies saved while Mozilla is running will getclobbered by Mozilla.\end{classdesc} \begin{classdesc}{LWPCookieJar}{filename, delayload=\constant{None}, policy=\constant{None}}A \class{FileCookieJar} that can load from and save cookies to disk informat compatible with the libwww-perl library's \code{Set-Cookie3}file format.  This is convenient if you want to store cookies in ahuman-readable file.\end{classdesc}  \subsection{CookiePolicy Objects \label{cookie-policy-objects}} Objects implementing the \class{CookiePolicy} interface have thefollowing methods: \begin{methoddesc}[CookiePolicy]{set_ok}{cookie, request}Return boolean value indicating whether cookie should be accepted from server. \var{cookie} is a \class{cookielib.Cookie} instance.  \var{request} isan object implementing the interface defined by the documentation for\method{CookieJar.extract_cookies()}.\end{methoddesc} \begin{methoddesc}[CookiePolicy]{return_ok}{cookie, request}Return boolean value indicating whether cookie should be returned to server. \var{cookie} is a \class{cookielib.Cookie} instance.  \var{request} isan object implementing the interface defined by the documentation for\method{CookieJar.add_cookie_header()}.\end{methoddesc} \begin{methoddesc}[CookiePolicy]{domain_return_ok}{domain, request}Return false if cookies should not be returned, given cookie domain. This method is an optimization.  It removes the need for checkingevery cookie with a particular domain (which might involve readingmany files).  Returning true from \method{domain_return_ok()} and\method{path_return_ok()} leaves all the work to \method{return_ok()}. If \method{domain_return_ok()} returns true for the cookie domain,\method{path_return_ok()} is called for the cookie path.  Otherwise,\method{path_return_ok()} and \method{return_ok()} are never calledfor that cookie domain.  If \method{path_return_ok()} returns true,\method{return_ok()} is called with the \class{Cookie} object itselffor a full check.  Otherwise, \method{return_ok()} is never called forthat cookie path. Note that \method{domain_return_ok()} is called for every\emph{cookie} domain, not just for the \emph{request} domain.  Forexample, the function might be called with both \code{".example.com"}and \code{"www.example.com"} if the request domain is\code{"www.example.com"}.  The same goes for\method{path_return_ok()}. The \var{request} argument is as documented for \method{return_ok()}.\end{methoddesc} \begin{methoddesc}[CookiePolicy]{path_return_ok}{path, request}Return false if cookies should not be returned, given cookie path. See the documentation for \method{domain_return_ok()}.\end{methoddesc}  In addition to implementing the methods above, implementations of the\class{CookiePolicy} interface must also supply the followingattributes, indicating which protocols should be used, and how.  Allof these attributes may be assigned to. \begin{memberdesc}{netscape}Implement Netscape protocol.\end{memberdesc}\begin{memberdesc}{rfc2965}Implement RFC 2965 protocol.\end{memberdesc}\begin{memberdesc}{hide_cookie2}Don't add \mailheader{Cookie2} header to requests (the presence ofthis header indicates to the server that we understand RFC 2965cookies).\end{memberdesc} The most useful way to define a \class{CookiePolicy} class is bysubclassing from \class{DefaultCookiePolicy} and overriding some orall of the methods above.  \class{CookiePolicy} itself may be used asa 'null policy' to allow setting and receiving any and all cookies(this is unlikely to be useful).  \subsection{DefaultCookiePolicy Objects \label{default-cookie-policy-objects}} Implements the standard rules for accepting and returning cookies. Both RFC 2965 and Netscape cookies are covered.  RFC 2965 handling isswitched off by default. The easiest way to provide your own policy is to override this classand call its methods in your overridden implementations before addingyour own additional checks: \begin{verbatim}import cookielibclass MyCookiePolicy(cookielib.DefaultCookiePolicy):    def set_ok(self, cookie, request):        if not cookielib.DefaultCookiePolicy.set_ok(self, cookie, request):            return False        if i_dont_want_to_store_this_cookie(cookie):            return False        return True\end{verbatim} In addition to the features required to implement the\class{CookiePolicy} interface, this class allows you to block andallow domains from setting and receiving cookies.  There are also somestrictness switches that allow you to tighten up the rather looseNetscape protocol rules a little bit (at the cost of blocking somebenign cookies). A domain blacklist and whitelist is provided (both off by default).Only domains not in the blacklist and present in the whitelist (if thewhitelist is active) participate in cookie setting and returning.  Usethe \var{blocked_domains} constructor argument, and\method{blocked_domains()} and \method{set_blocked_domains()} methods(and the corresponding argument and methods for\var{allowed_domains}).  If you set a whitelist, you can turn it offagain by setting it to \constant{None}. Domains in block or allow lists that do not start with a dot mustequal the cookie domain to be matched.  For example,\code{"example.com"} matches a blacklist entry of\code{"example.com"}, but \code{"www.example.com"} does not.  Domainsthat do start with a dot are matched by more specific domains too.For example, both \code{"www.example.com"} and\code{"www.coyote.example.com"} match \code{".example.com"} (but\code{"example.com"} itself does not).  IP addresses are an exception,and must match exactly.  For example, if blocked_domains contains\code{"192.168.1.2"} and \code{".168.1.2"}, 192.168.1.2 is blocked,but 193.168.1.2 is not. \class{DefaultCookiePolicy} implements the following additionalmethods: \begin{methoddesc}[DefaultCookiePolicy]{blocked_domains}{}Return the sequence of blocked domains (as a tuple).\end{methoddesc} \begin{methoddesc}[DefaultCookiePolicy]{set_blocked_domains}  {blocked_domains}Set the sequence of blocked domains.\end{methoddesc} \begin{methoddesc}[DefaultCookiePolicy]{is_blocked}{domain}Return whether \var{domain} is on the blacklist for setting orreceiving cookies.\end{methoddesc} \begin{methoddesc}[DefaultCookiePolicy]{allowed_domains}{}Return \constant{None}, or the sequence of allowed domains (as a tuple).\end{methoddesc} \begin{methoddesc}[DefaultCookiePolicy]{set_allowed_domains}  {allowed_domains}Set the sequence of allowed domains, or \constant{None}.\end{methoddesc} \begin{methoddesc}[DefaultCookiePolicy]{is_not_allowed}{domain}Return whether \var{domain} is not on the whitelist for setting orreceiving cookies.

Lines 1–500 of 720.