Martin v. Löwis | 2a6ba90 | 2004-05-31 18:22:40 +0000 | [diff] [blame^] | 1 | \section{\module{cookielib} --- |
| 2 | Cookie handling for HTTP clients} |
| 3 | |
| 4 | \declaremodule{standard}{cookielib} |
| 5 | \moduleauthor{John J. Lee}{jjl@pobox.com} |
| 6 | \sectionauthor{John J. Lee}{jjl@pobox.com} |
| 7 | |
| 8 | \modulesynopsis{Cookie handling for HTTP clients} |
| 9 | |
| 10 | The \module{cookielib} module defines classes for automatic handling |
| 11 | of HTTP cookies. It is useful for accessing web sites that require |
| 12 | small pieces of data -- \dfn{cookies} -- to be set on the client |
| 13 | machine by an HTTP response from a web server, and then returned to |
| 14 | the server in later HTTP requests. |
| 15 | |
| 16 | Both the regular Netscape cookie protocol and the protocol defined by |
| 17 | \rfc{2965} are handled. RFC 2965 handling is switched off by default. |
| 18 | \rfc{2109} cookies are parsed as Netscape cookies and subsequently |
| 19 | treated as RFC 2965 cookies. Note that the great majority of cookies |
| 20 | on the Internet are Netscape cookies. \module{cookielib} attempts to |
| 21 | follow the de-facto Netscape cookie protocol (which differs |
| 22 | substantially from that set out in the original Netscape |
| 23 | specification), including taking note of the \code{max-age} and |
| 24 | \code{port} cookie-attributes introduced with RFC 2109. \note{The |
| 25 | various named parameters found in \mailheader{Set-Cookie} and |
| 26 | \mailheader{Set-Cookie2} headers (eg. \code{domain} and |
| 27 | \code{expires}) are conventionally referred to as \dfn{attributes}. |
| 28 | To distinguish them from Python attributes, the documentation for this |
| 29 | module uses the term \dfn{cookie-attribute} instead}. |
| 30 | |
| 31 | |
| 32 | The module defines the following exception: |
| 33 | |
| 34 | \begin{excdesc}{LoadError} |
| 35 | Instances of \class{FileCookieJar} raise this exception on failure to |
| 36 | load cookies from a file. |
| 37 | \end{excdesc} |
| 38 | |
| 39 | |
| 40 | The following classes are provided: |
| 41 | |
| 42 | \begin{classdesc}{CookieJar}{policy=\constant{None}} |
| 43 | \var{policy} is an object implementing the \class{CookiePolicy} |
| 44 | interface. |
| 45 | |
| 46 | The \class{CookieJar} class stores HTTP cookies. It extracts cookies |
| 47 | from HTTP requests, and returns them in HTTP responses. |
| 48 | \class{CookieJar} instances automatically expire contained cookies |
| 49 | when necessary. Subclasses are also responsible for storing and |
| 50 | retrieving cookies from a file or database. |
| 51 | \end{classdesc} |
| 52 | |
| 53 | \begin{classdesc}{FileCookieJar}{filename, delayload=\constant{None}, |
| 54 | policy=\constant{None}} |
| 55 | \var{policy} is an object implementing the \class{CookiePolicy} |
| 56 | interface. For the other arguments, see the documentation for the |
| 57 | corresponding attributes. |
| 58 | |
| 59 | A \class{CookieJar} which can load cookies from, and perhaps save |
| 60 | cookies to, a file on disk. Cookies are \strong{NOT} loaded from the |
| 61 | named file until either the \method{load()} or \method{revert()} |
| 62 | method is called. Subclasses of this class are documented in section |
| 63 | \ref{file-cookie-jar-classes}. |
| 64 | \end{classdesc} |
| 65 | |
| 66 | \begin{classdesc}{CookiePolicy}{} |
| 67 | This class is responsible for deciding whether each cookie should be |
| 68 | accepted from / returned to the server. |
| 69 | \end{classdesc} |
| 70 | |
| 71 | \begin{classdesc}{DefaultCookiePolicy}{ |
| 72 | blocked_domains=\constant{None}, |
| 73 | allowed_domains=\constant{None}, |
| 74 | netscape=\constant{True}, rfc2965=\constant{False}, |
| 75 | hide_cookie2=\constant{False}, |
| 76 | strict_domain=\constant{False}, |
| 77 | strict_rfc2965_unverifiable=\constant{True}, |
| 78 | strict_ns_unverifiable=\constant{False}, |
| 79 | strict_ns_domain=\constant{DefaultCookiePolicy.DomainLiberal}, |
| 80 | strict_ns_set_initial_dollar=\constant{False}, |
| 81 | strict_ns_set_path=\constant{False} |
| 82 | } |
| 83 | |
| 84 | Constructor arguments should be passed as keyword arguments only. |
| 85 | \var{blocked_domains} is a sequence of domain names that we never |
| 86 | accept cookies from, nor return cookies to. \var{allowed_domains} if |
| 87 | not \constant{None}, this is a sequence of the only domains for which |
| 88 | we accept and return cookies. For all other arguments, see the |
| 89 | documentation for \class{CookiePolicy} and \class{DefaultCookiePolicy} |
| 90 | objects. |
| 91 | |
| 92 | \class{DefaultCookiePolicy} implements the standard accept / reject |
| 93 | rules for Netscape and RFC 2965 cookies. RFC 2109 cookies |
| 94 | (ie. cookies received in a \mailheader{Set-Cookie} header with a |
| 95 | version cookie-attribute of 1) are treated according to the RFC 2965 |
| 96 | rules. \class{DefaultCookiePolicy} also provides some parameters to |
| 97 | allow some fine-tuning of policy. |
| 98 | \end{classdesc} |
| 99 | |
| 100 | \begin{classdesc}{Cookie}{} |
| 101 | This class represents Netscape, RFC 2109 and RFC 2965 cookies. It is |
| 102 | not expected that users of \module{cookielib} construct their own |
| 103 | \class{Cookie} instances. Instead, if necessary, call |
| 104 | \method{make_cookies()} on a \class{CookieJar} instance. |
| 105 | \end{classdesc} |
| 106 | |
| 107 | \begin{seealso} |
| 108 | |
| 109 | \seemodule{urllib2}{URL opening with automatic cookie handling.} |
| 110 | |
| 111 | \seemodule{Cookie}{HTTP cookie classes, principally useful for |
| 112 | server-side code. The \module{cookielib} and \module{Cookie} modules |
| 113 | do not depend on each other.} |
| 114 | |
| 115 | \seeurl{http://wwwsearch.sf.net/ClientCookie/}{Extensions to this |
| 116 | module, including a class for reading Microsoft Internet Explorer |
| 117 | cookies on Windows.} |
| 118 | |
| 119 | \seeurl{http://www.netscape.com/newsref/std/cookie_spec.html}{The |
| 120 | specification of the original Netscape cookie protocol. Though this |
| 121 | is still the dominant protocol, the 'Netscape cookie protocol' |
| 122 | implemented by all the major browsers (and \module{cookielib}) only |
| 123 | bears a passing resemblance to the one sketched out in |
| 124 | \code{cookie_spec.html}.} |
| 125 | |
| 126 | \seerfc{2109}{HTTP State Management Mechanism}{Obsoleted by RFC 2965. |
| 127 | Uses \mailheader{Set-Cookie} with version=1.} |
| 128 | |
| 129 | \seerfc{2965}{HTTP State Management Mechanism}{The Netscape protocol |
| 130 | with the bugs fixed. Uses \mailheader{Set-Cookie2} in place of |
| 131 | \mailheader{Set-Cookie}. Not widely used.} |
| 132 | |
| 133 | \seeurl{http://kristol.org/cookie/errata.html}{Unfinished errata to |
| 134 | RFC 2965.} |
| 135 | |
| 136 | \seerfc{2964}{Use of HTTP State Management}{} |
| 137 | |
| 138 | \end{seealso} |
| 139 | |
| 140 | |
| 141 | \subsection{CookieJar and FileCookieJar Objects \label{cookie-jar-objects}} |
| 142 | |
| 143 | \class{CookieJar} objects support the iterator protocol. |
| 144 | |
| 145 | \class{CookieJar} has the following methods: |
| 146 | |
| 147 | \begin{methoddesc}[CookieJar]{add_cookie_header}{request} |
| 148 | Add correct \mailheader{Cookie} header to \var{request}. |
| 149 | |
| 150 | If the CookiePolicy allows (ie. the \class{CookiePolicy} instance's |
| 151 | \member{rfc2965} and \member{hide_cookie2} attributes are true and |
| 152 | false respectively), the \mailheader{Cookie2} header is also added |
| 153 | when appropriate. |
| 154 | |
| 155 | The \var{request} object (usually a \class{urllib2.Request} instance) |
| 156 | must support the methods \method{get_full_url()}, \method{get_host()}, |
| 157 | \method{get_type()}, \method{unverifiable()}, |
| 158 | \method{get_origin_req_host()}, \method{has_header()}, |
| 159 | \method{get_header()}, \method{header_items()}, and |
| 160 | \method{add_unredirected_header()},as documented by \module{urllib2}. |
| 161 | \end{methoddesc} |
| 162 | |
| 163 | \begin{methoddesc}[CookieJar]{extract_cookies}{response, request} |
| 164 | Extract cookies from HTTP \var{response} and store them in the |
| 165 | \class{CookieJar}, where allowed by policy. |
| 166 | |
| 167 | The \class{CookieJar} will look for allowable \mailheader{Set-Cookie} |
| 168 | and \mailheader{Set-Cookie2} headers in the \var{response} argument, |
| 169 | and store cookies as appropriate (subject to the |
| 170 | \method{CookiePolicy.set_ok()} method's approval). |
| 171 | |
| 172 | The \var{response} object (usually the result of a call to |
| 173 | \method{urllib2.urlopen()}, or similar) should support an |
| 174 | \method{info()} method, which returns an object with a |
| 175 | \method{getallmatchingheaders()} method (usually a |
| 176 | \class{mimetools.Message} instance). |
| 177 | |
| 178 | The \var{request} object (usually a \class{urllib2.Request} instance) |
| 179 | must support the methods \method{get_full_url()}, \method{get_host()}, |
| 180 | \method{unverifiable()}, and \method{get_origin_req_host()}, as |
| 181 | documented by \module{urllib2}. The request is used to set default |
| 182 | values for cookie-attributes as well as for checking that the cookie |
| 183 | is allowed to be set. |
| 184 | \end{methoddesc} |
| 185 | |
| 186 | \begin{methoddesc}[CookieJar]{set_policy}{policy} |
| 187 | Set the \class{CookiePolicy} instance to be used. |
| 188 | \end{methoddesc} |
| 189 | |
| 190 | \begin{methoddesc}[CookieJar]{make_cookies}{response, request} |
| 191 | Return sequence of \class{Cookie} objects extracted from |
| 192 | \var{response} object. |
| 193 | |
| 194 | See the documentation for \method{extract_cookies} for the interfaces |
| 195 | required of the \var{response} and \var{request} arguments. |
| 196 | \end{methoddesc} |
| 197 | |
| 198 | \begin{methoddesc}[CookieJar]{set_cookie_if_ok}{cookie, request} |
| 199 | Set a \class{Cookie} if policy says it's OK to do so. |
| 200 | \end{methoddesc} |
| 201 | |
| 202 | \begin{methoddesc}[CookieJar]{set_cookie}{cookie} |
| 203 | Set a \class{Cookie}, without checking with policy to see whether or |
| 204 | not it should be set. |
| 205 | \end{methoddesc} |
| 206 | |
| 207 | \begin{methoddesc}[CookieJar]{clear}{\optional{domain\optional{, |
| 208 | path\optional{, name}}}} |
| 209 | Clear some cookies. |
| 210 | |
| 211 | If invoked without arguments, clear all cookies. If given a single |
| 212 | argument, only cookies belonging to that \var{domain} will be removed. |
| 213 | If given two arguments, cookies belonging to the specified |
| 214 | \var{domain} and URL \var{path} are removed. If given three |
| 215 | arguments, then the cookie with the specified \var{domain}, \var{path} |
| 216 | and \var{name} is removed. |
| 217 | |
| 218 | Raises \exception{KeyError} if no matching cookie exists. |
| 219 | \end{methoddesc} |
| 220 | |
| 221 | \begin{methoddesc}[CookieJar]{clear_session_cookies}{} |
| 222 | Discard all session cookies. |
| 223 | |
| 224 | Discards all contained cookies that have a true \member{discard} |
| 225 | attribute (usually because they had either no \code{max-age} or |
| 226 | \code{expires} cookie-attribute, or an explicit \code{discard} |
| 227 | cookie-attribute). For interactive browsers, the end of a session |
| 228 | usually corresponds to closing the browser window. |
| 229 | |
| 230 | Note that the \method{save()} method won't save session cookies |
| 231 | anyway, unless you ask otherwise by passing a true |
| 232 | \var{ignore_discard} argument. |
| 233 | \end{methoddesc} |
| 234 | |
| 235 | \class{FileCookieJar} implements the following additional methods: |
| 236 | |
| 237 | \begin{methoddesc}[FileCookieJar]{save}{filename=\constant{None}, |
| 238 | ignore_discard=\constant{False}, ignore_expires=\constant{False}} |
| 239 | Save cookies to a file. |
| 240 | |
| 241 | This base class raises \class{NotImplementedError}. Subclasses may |
| 242 | leave this method unimplemented. |
| 243 | |
| 244 | \var{filename} is the name of file in which to save cookies. If |
| 245 | \var{filename} is not specified, \member{self.filename} is used (whose |
| 246 | default is the value passed to the constructor, if any); if |
| 247 | \member{self.filename} is \constant{None}, \exception{ValueError} is |
| 248 | raised. |
| 249 | |
| 250 | \var{ignore_discard}: save even cookies set to be discarded. |
| 251 | \var{ignore_expires}: save even cookies that have expired |
| 252 | |
| 253 | The file is overwritten if it already exists, thus wiping all the |
| 254 | cookies it contains. Saved cookies can be restored later using the |
| 255 | \method{load()} or \method{revert()} methods. |
| 256 | \end{methoddesc} |
| 257 | |
| 258 | \begin{methoddesc}[FileCookieJar]{load}{filename=\constant{None}, |
| 259 | ignore_discard=\constant{False}, ignore_expires=\constant{False}} |
| 260 | Load cookies from a file. |
| 261 | |
| 262 | Old cookies are kept unless overwritten by newly loaded ones. |
| 263 | |
| 264 | Arguments are as for \method{save()}. |
| 265 | |
| 266 | The named file must be in the format understood by the class, or |
| 267 | \exception{LoadError} will be raised. |
| 268 | \end{methoddesc} |
| 269 | |
| 270 | \begin{methoddesc}[FileCookieJar]{revert}{filename=\constant{None}, |
| 271 | ignore_discard=\constant{False}, ignore_expires=\constant{False}} |
| 272 | Clear all cookies and reload cookies from a saved file. |
| 273 | |
| 274 | Raises \exception{cookielib.LoadError} or \exception{IOError} if |
| 275 | reversion is not successful; the object's state will not be altered if |
| 276 | this happens. |
| 277 | \end{methoddesc} |
| 278 | |
| 279 | \class{FileCookieJar} instances have the following public attributes: |
| 280 | |
| 281 | \begin{memberdesc}{filename} |
| 282 | Filename of default file in which to keep cookies. |
| 283 | \end{memberdesc} |
| 284 | |
| 285 | \begin{memberdesc}{delayload} |
| 286 | If true, load cookies lazily from disk. This is only a hint, since |
| 287 | this only affects performance, not behaviour (unless the cookies on |
| 288 | disk are changing). A \class{CookieJar} object may ignore it. None |
| 289 | of the \class{FileCookieJar} classes included in the standard library |
| 290 | lazily loads cookies. |
| 291 | \end{memberdesc} |
| 292 | |
| 293 | |
| 294 | \subsection{FileCookieJar subclasses and co-operation with web browsers |
| 295 | \label{file-cookie-jar-classes}} |
| 296 | |
| 297 | The following \class{CookieJar} subclasses are provided for reading |
| 298 | and writing . Further \class{CookieJar} subclasses, including one |
| 299 | that reads Microsoft Internet Explorer cookies, are available at |
| 300 | \url{http://wwwsearch.sf.net/ClientCookie/}. |
| 301 | |
| 302 | \begin{classdesc}{MozillaCookieJar}{filename, delayload=\constant{None}, |
| 303 | policy=\constant{None}} |
| 304 | A \class{FileCookieJar} that can load from and save cookies to disk in |
| 305 | the Mozilla \code{cookies.txt} file format (which is also used by the |
| 306 | lynx and Netscape browsers). \note{This loses information about RFC |
| 307 | 2965 cookies, and also about newer or non-standard cookie-attributes |
| 308 | such as \code{port}.} |
| 309 | |
| 310 | \warning{Back up your cookies before saving if you have cookies whose |
| 311 | loss / corruption would be inconvenient (there are some subtleties |
| 312 | which may lead to slight changes in the file over a load / save |
| 313 | round-trip).} |
| 314 | |
| 315 | Also note that cookies saved while Mozilla is running will get |
| 316 | clobbered by Mozilla. |
| 317 | \end{classdesc} |
| 318 | |
| 319 | \begin{classdesc}{LWPCookieJar}{filename, delayload=\constant{None}, |
| 320 | policy=\constant{None}} |
| 321 | A \class{FileCookieJar} that can load from and save cookies to disk in |
| 322 | format compatible with the libwww-perl library's \code{Set-Cookie3} |
| 323 | file format. This is convenient if you want to store cookies in a |
| 324 | human-readable file. |
| 325 | \end{classdesc} |
| 326 | |
| 327 | |
| 328 | \subsection{CookiePolicy Objects \label{cookie-policy-objects}} |
| 329 | |
| 330 | Objects implementing the \class{CookiePolicy} interface have the |
| 331 | following methods: |
| 332 | |
| 333 | \begin{methoddesc}[CookiePolicy]{set_ok}{cookie, request} |
| 334 | Return boolean value indicating whether cookie should be accepted from server. |
| 335 | |
| 336 | \var{cookie} is a \class{cookielib.Cookie} instance. \var{request} is |
| 337 | an object implementing the interface defined by the documentation for |
| 338 | \method{CookieJar.extract_cookies()}. |
| 339 | \end{methoddesc} |
| 340 | |
| 341 | \begin{methoddesc}[CookiePolicy]{return_ok}{cookie, request} |
| 342 | Return boolean value indicating whether cookie should be returned to server. |
| 343 | |
| 344 | \var{cookie} is a \class{cookielib.Cookie} instance. \var{request} is |
| 345 | an object implementing the interface defined by the documentation for |
| 346 | \method{CookieJar.add_cookie_header()}. |
| 347 | \end{methoddesc} |
| 348 | |
| 349 | \begin{methoddesc}[CookiePolicy]{domain_return_ok}{domain, request} |
| 350 | Return false if cookies should not be returned, given cookie domain. |
| 351 | |
| 352 | This method is an optimization. It removes the need for checking |
| 353 | every cookie with a particular domain (which might involve reading |
| 354 | many files). The default implementations of |
| 355 | \method{domain_return_ok()} and \method{path_return_ok()} |
| 356 | (\samp{return True}) leave all the work to \method{return_ok()}. |
| 357 | |
| 358 | If \method{domain_return_ok()} returns true for the cookie domain, |
| 359 | \method{path_return_ok()} is called for the cookie path. Otherwise, |
| 360 | \method{path_return_ok()} and \method{return_ok()} are never called |
| 361 | for that cookie domain. If \method{path_return_ok()} returns true, |
| 362 | \method{return_ok()} is called with the \class{Cookie} object itself |
| 363 | for a full check. Otherwise, \method{return_ok()} is never called for |
| 364 | that cookie path. |
| 365 | |
| 366 | Note that \method{domain_return_ok()} is called for every |
| 367 | \emph{cookie} domain, not just for the \emph{request} domain. For |
| 368 | example, the function might be called with both \code{".example.com"} |
| 369 | and \code{"www.example.com"} if the request domain is |
| 370 | \code{"www.example.com"}. The same goes for |
| 371 | \method{path_return_ok()}. |
| 372 | |
| 373 | The \var{request} argument is as documented for \method{return_ok()}. |
| 374 | \end{methoddesc} |
| 375 | |
| 376 | \begin{methoddesc}[CookiePolicy]{path_return_ok}{path, request} |
| 377 | Return false if cookies should not be returned, given cookie path. |
| 378 | |
| 379 | See the documentation for \method{domain_return_ok()}. |
| 380 | \end{methoddesc} |
| 381 | |
| 382 | |
| 383 | In addition to implementing the methods above, implementations of the |
| 384 | \class{CookiePolicy} interface must also supply the following |
| 385 | attributes, indicating which protocols should be used, and how. All |
| 386 | of these attributes may be assigned to. |
| 387 | |
| 388 | \begin{memberdesc}{netscape} |
| 389 | Implement netscape protocol. |
| 390 | \end{memberdesc} |
| 391 | \begin{memberdesc}{rfc2965} |
| 392 | Implement RFC 2965 protocol. |
| 393 | \end{memberdesc} |
| 394 | \begin{memberdesc}{hide_cookie2} |
| 395 | Don't add Cookie2 header to requests (the presence of this header |
| 396 | indicates to the server that we understand RFC 2965 cookies). |
| 397 | \end{memberdesc} |
| 398 | |
| 399 | The most useful way to define a \class{CookiePolicy} class is by |
| 400 | subclassing from \class{DefaultCookiePolicy} and overriding some or |
| 401 | all of the methods above. \class{CookiePolicy} itself may be used as |
| 402 | a 'null policy' to allow setting and receiving any and all cookies. |
| 403 | |
| 404 | |
| 405 | \subsection{DefaultCookiePolicy Objects \label{default-cookie-policy-objects}} |
| 406 | |
| 407 | Implements the standard rules for accepting and returning cookies. |
| 408 | |
| 409 | Both RFC 2965 and Netscape cookies are covered. RFC 2965 handling is |
| 410 | switched off by default. |
| 411 | |
| 412 | The easiest way to provide your own policy is to override this class |
| 413 | and call its methods in your overriden implementations before adding |
| 414 | your own additional checks: |
| 415 | |
| 416 | \begin{verbatim} |
| 417 | import cookielib |
| 418 | class MyCookiePolicy(cookielib.DefaultCookiePolicy): |
| 419 | def set_ok(self, cookie, request): |
| 420 | if not cookielib.DefaultCookiePolicy.set_ok(self, cookie, request): |
| 421 | return False |
| 422 | if i_dont_want_to_store_this_cookie(cookie): |
| 423 | return False |
| 424 | return True |
| 425 | \end{verbatim} |
| 426 | |
| 427 | In addition to the features required to implement the |
| 428 | \class{CookiePolicy} interface, this class allows you to block and |
| 429 | allow domains from setting and receiving cookies. There are also some |
| 430 | strictness switches that allow you to tighten up the rather loose |
| 431 | Netscape protocol rules a little bit (at the cost of blocking some |
| 432 | benign cookies). |
| 433 | |
| 434 | A domain blacklist and whitelist is provided (both off by default). |
| 435 | Only domains not in the blacklist and present in the whitelist (if the |
| 436 | whitelist is active) participate in cookie setting and returning. Use |
| 437 | the \var{blocked_domains} constructor argument, and |
| 438 | \method{blocked_domains()} and \method{set_blocked_domains()} methods |
| 439 | (and the corresponding argument and methods for |
| 440 | \var{allowed_domains}). If you set a whitelist, you can turn it off |
| 441 | again by setting it to \constant{None}. |
| 442 | |
| 443 | Domains in block or allow lists that do not start with a dot must be |
| 444 | equal. For example, \code{"example.com"} matches a blacklist entry of |
| 445 | \code{"example.com"}, but \code{"www.example.com"} does not. Domains |
| 446 | that do start with a dot are matched by more specific domains too. |
| 447 | For example, both \code{"www.example.com"} and |
| 448 | \code{"www.coyote.example.com"} match \code{".example.com"} (but |
| 449 | \code{"example.com"} itself does not). IP addresses are an exception, |
| 450 | and must match exactly. For example, if blocked_domains contains |
| 451 | \code{"192.168.1.2"} and \code{".168.1.2"}, 192.168.1.2 is blocked, |
| 452 | but 193.168.1.2 is not. |
| 453 | |
| 454 | \class{DefaultCookiePolicy} implements the following additional |
| 455 | methods: |
| 456 | |
| 457 | \begin{methoddesc}[DefaultCookiePolicy]{blocked_domains}{} |
| 458 | Return the sequence of blocked domains (as a tuple). |
| 459 | \end{methoddesc} |
| 460 | |
| 461 | \begin{methoddesc}[DefaultCookiePolicy]{set_blocked_domains} |
| 462 | {blocked_domains} |
| 463 | Set the sequence of blocked domains. |
| 464 | \end{methoddesc} |
| 465 | |
| 466 | \begin{methoddesc}[DefaultCookiePolicy]{is_blocked}{domain} |
| 467 | Return whether \var{domain} is on the blacklist for setting or |
| 468 | receiving cookies. |
| 469 | \end{methoddesc} |
| 470 | |
| 471 | \begin{methoddesc}[DefaultCookiePolicy]{allowed_domains}{} |
| 472 | Return \constant{None}, or the sequence of allowed domains (as a tuple). |
| 473 | \end{methoddesc} |
| 474 | |
| 475 | \begin{methoddesc}[DefaultCookiePolicy]{set_allowed_domains} |
| 476 | {allowed_domains} |
| 477 | Set the sequence of allowed domains, or \constant{None}. |
| 478 | \end{methoddesc} |
| 479 | |
| 480 | \begin{methoddesc}[DefaultCookiePolicy]{is_not_allowed}{domain} |
| 481 | Return whether \var{domain} is not on the whitelist for setting or |
| 482 | receiving cookies. |
| 483 | \end{methoddesc} |
| 484 | |
| 485 | \class{DefaultCookiePolicy} instances have the following attributes, |
| 486 | which are all initialised from the constructor arguments of the same |
| 487 | name, and which may all be assigned to. |
| 488 | |
| 489 | General strictness switches: |
| 490 | |
| 491 | \begin{memberdesc}{strict_domain} |
| 492 | Don't allow sites to set two-component domains with country-code |
| 493 | top-level domains like \code{.co.uk}, \code{.gov.uk}, |
| 494 | \code{.co.nz}.etc. This is far from perfect and isn't guaranteed to |
| 495 | work! |
| 496 | \end{memberdesc} |
| 497 | |
| 498 | RFC 2965 protocol strictness switches: |
| 499 | |
| 500 | \begin{memberdesc}{strict_rfc2965_unverifiable} |
| 501 | Follow RFC 2965 rules on unverifiable transactions (usually, an |
| 502 | unverifiable transaction is one resulting from a redirect or a request |
| 503 | for an image hosted on another site). If this is false, cookies are |
| 504 | \emph{never} blocked on the basis of verifiability |
| 505 | \end{memberdesc} |
| 506 | |
| 507 | Netscape protocol strictness switches: |
| 508 | |
| 509 | \begin{memberdesc}{strict_ns_unverifiable} |
| 510 | apply RFC 2965 rules on unverifiable transactions even to Netscape |
| 511 | cookies |
| 512 | \end{memberdesc} |
| 513 | \begin{memberdesc}{strict_ns_domain} |
| 514 | Flags indicating how strict to be with domain-matching rules for |
| 515 | Netscape cookies. See below for acceptable values. |
| 516 | \end{memberdesc} |
| 517 | \begin{memberdesc}{strict_ns_set_initial_dollar} |
| 518 | Ignore cookies in Set-Cookie: headers that have names starting with |
| 519 | \code{'\$'}. |
| 520 | \end{memberdesc} |
| 521 | \begin{memberdesc}{strict_ns_set_path} |
| 522 | Don't allow setting cookies whose path doesn't path-match request URI. |
| 523 | \end{memberdesc} |
| 524 | |
| 525 | \member{strict_ns_domain} is a collection of flags. Its value is |
| 526 | constructed by or-ing together (for example, |
| 527 | \code{DomainStrictNoDots|DomainStrictNonDomain} means both flags are |
| 528 | set). |
| 529 | |
| 530 | \begin{memberdesc}{DomainStrictNoDots} |
| 531 | When setting cookies, the 'host prefix' must not contain a dot |
| 532 | (eg. \code{www.foo.bar.com} can't set a cookie for \code{.bar.com}, |
| 533 | because \code{www.foo} contains a dot). |
| 534 | \end{memberdesc} |
| 535 | \begin{memberdesc}{DomainStrictNonDomain} |
| 536 | Cookies that did not explicitly specify a \code{domain} |
| 537 | cookie-attribute can only be returned to a domain that string-compares |
| 538 | equal to the domain that set the cookie (eg. \code{spam.example.com} |
| 539 | won't be returned cookies from \code{example.com} that had no |
| 540 | \code{domain} cookie-attribute). |
| 541 | \end{memberdesc} |
| 542 | \begin{memberdesc}{DomainRFC2965Match} |
| 543 | When setting cookies, require a full RFC 2965 domain-match. |
| 544 | \end{memberdesc} |
| 545 | |
| 546 | The following attributes are provided for convenience, and are the |
| 547 | most useful combinations of the above flags: |
| 548 | |
| 549 | \begin{memberdesc}{DomainLiberal} |
| 550 | Equivalent to 0 (ie. all of the above Netscape domain strictness flags |
| 551 | switched off). |
| 552 | \end{memberdesc} |
| 553 | \begin{memberdesc}{DomainStrict} |
| 554 | Equivalent to \code{DomainStrictNoDots|DomainStrictNonDomain}. |
| 555 | \end{memberdesc} |
| 556 | |
| 557 | |
| 558 | \subsection{Cookie Objects \label{cookie-jar-objects}} |
| 559 | |
| 560 | \class{Cookie} instances have Python attributes roughly corresponding |
| 561 | to the standard cookie-attributes specified in the various cookie |
| 562 | standards. The correspondence is not one-to-one, because there are |
| 563 | complicated rules for assigning default values, and because the |
| 564 | \code{max-age} and \code{expires} cookie-attributes contain equivalent |
| 565 | information. |
| 566 | |
| 567 | Assignment to these attributes should not be necessary other than in |
| 568 | rare circumstances in a \class{CookiePolicy} method. The class does |
| 569 | not enforce internal consistency, so you should know what you're |
| 570 | doing if you do that. |
| 571 | |
| 572 | \begin{memberdesc}[Cookie]{version} |
| 573 | Integer or \constant{None}. Netscape cookies have version 0. RFC |
| 574 | 2965 and RFC 2109 cookies have version 1. |
| 575 | \end{memberdesc} |
| 576 | \begin{memberdesc}[Cookie]{name} |
| 577 | Cookie name (a string), or \constant{None}. |
| 578 | \end{memberdesc} |
| 579 | \begin{memberdesc}[Cookie]{value} |
| 580 | Cookie value (a string). |
| 581 | \end{memberdesc} |
| 582 | \begin{memberdesc}[Cookie]{port} |
| 583 | String representing a port or a set of ports (eg. '80', or '80,8080'), |
| 584 | or \constant{None}. |
| 585 | \end{memberdesc} |
| 586 | \begin{memberdesc}[Cookie]{path} |
| 587 | Cookie path (a string, eg. '/acme/rocket_launchers'). |
| 588 | \end{memberdesc} |
| 589 | \begin{memberdesc}[Cookie]{secure} |
| 590 | True if cookie should only be returned over a secure connection. |
| 591 | \end{memberdesc} |
| 592 | \begin{memberdesc}[Cookie]{expires} |
| 593 | Integer expiry date in seconds since epoch, or \constant{None}. See |
| 594 | also the \method{is_expired()} method. |
| 595 | \end{memberdesc} |
| 596 | \begin{memberdesc}[Cookie]{discard} |
| 597 | True if this is a session cookie. |
| 598 | \end{memberdesc} |
| 599 | \begin{memberdesc}[Cookie]{comment} |
| 600 | String comment from the server explaining the function of this cookie, |
| 601 | or \constant{None}. |
| 602 | \end{memberdesc} |
| 603 | \begin{memberdesc}[Cookie]{comment_url} |
| 604 | URL linking to a comment from the server explaining the function of |
| 605 | this cookie, or \constant{None}. |
| 606 | \end{memberdesc} |
| 607 | |
| 608 | \begin{memberdesc}[Cookie]{port_specified} |
| 609 | True if a port or set of ports was explicitly specified by the server |
| 610 | (in the \mailheader{Set-Cookie} / \mailheader{Set-Cookie2} header). |
| 611 | \end{memberdesc} |
| 612 | \begin{memberdesc}[Cookie]{domain_specified} |
| 613 | True if a domain was explicitly specified by the server. |
| 614 | \end{memberdesc} |
| 615 | \begin{memberdesc}[Cookie]{domain_initial_dot} |
| 616 | True if the domain explicitly specified by the server began with a |
| 617 | dot ('.'). |
| 618 | \end{memberdesc} |
| 619 | |
| 620 | Cookies may have additional non-standard cookie-attributes. These may |
| 621 | be accessed using the following methods: |
| 622 | |
| 623 | \begin{methoddesc}[Cookie]{has_nonstandard_attr}{name} |
| 624 | Return true if cookie has the named cookie-attribute. |
| 625 | \end{methoddesc} |
| 626 | \begin{methoddesc}[Cookie]{get_nonstandard_attr}{name, default=\constant{None}} |
| 627 | If cookie has the named cookie-attribute, return its value. |
| 628 | Otherwise, return \var{default}. |
| 629 | \end{methoddesc} |
| 630 | \begin{methoddesc}[Cookie]{set_nonstandard_attr}{name, value} |
| 631 | Set the value of the named cookie-attribute. |
| 632 | \end{methoddesc} |
| 633 | |
| 634 | The \class{Cookie} class also defines the following method: |
| 635 | |
| 636 | \begin{methoddesc}[Cookie]{is_expired}{\optional{now=\constant{None}}} |
| 637 | True if cookie has passed the time at which the server requested it |
| 638 | should expire. If \var{now} is given (in seconds since the epoch), |
| 639 | return whether the cookie has expired at the specified time. |
| 640 | \end{methoddesc} |
| 641 | |
| 642 | |
| 643 | \subsection{Examples \label{cookielib-examples}} |
| 644 | |
| 645 | The first example shows the most common usage of \module{cookielib}: |
| 646 | |
| 647 | \begin{verbatim} |
| 648 | import cookielib, urllib2 |
| 649 | cj = cookielib.CookieJar() |
| 650 | opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) |
| 651 | r = opener.open("http://example.com/") |
| 652 | \end{verbatim} |
| 653 | |
| 654 | This example illustrates how to open a URL using your Netscape, |
| 655 | Mozilla, or lynx cookies (assumes \UNIX{} convention for location of |
| 656 | the cookies file): |
| 657 | |
| 658 | \begin{verbatim} |
| 659 | import os, cookielib, urllib2 |
| 660 | cj = cookielib.MozillaCookieJar() |
| 661 | cj.load(os.path.join(os.environ["HOME"], "/.netscape/cookies.txt")) |
| 662 | opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) |
| 663 | r = opener.open("http://example.com/") |
| 664 | \end{verbatim} |
| 665 | |
| 666 | The next example illustrates the use of \class{DefaultCookiePolicy}. |
| 667 | Turn on RFC 2965 cookies, be more strict about domains when setting |
| 668 | and returning Netscape cookies, and block some domains from setting |
| 669 | cookies or having them returned: |
| 670 | |
| 671 | \begin{verbatim} |
| 672 | import urllib2 |
| 673 | from cookielib import CookieJar, DefaultCookiePolicy as Policy |
| 674 | policy = Policy(rfc2965=True, strict_ns_domain=Policy.DomainStrict, |
| 675 | blocked_domains=["ads.net", ".ads.net"]) |
| 676 | cj = CookieJar(policy) |
| 677 | opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj)) |
| 678 | r = opener.open("http://example.com/") |
| 679 | \end{verbatim} |