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