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