/Doc/library/cookielib.rst

http://unladen-swallow.googlecode.com/ · ReStructuredText · 777 lines · 470 code · 307 blank · 0 comment · 0 complexity · 7896410907a368f66f8c939909c021f7 MD5 · raw file

  1. :mod:`cookielib` --- Cookie handling for HTTP clients
  2. =====================================================
  3. .. module:: cookielib
  4. :synopsis: Classes for automatic handling of HTTP cookies.
  5. .. moduleauthor:: John J. Lee <jjl@pobox.com>
  6. .. sectionauthor:: John J. Lee <jjl@pobox.com>
  7. .. note::
  8. The :mod:`cookielib` module has been renamed to :mod:`http.cookiejar` in
  9. Python 3.0. The :term:`2to3` tool will automatically adapt imports when
  10. converting your sources to 3.0.
  11. .. versionadded:: 2.4
  12. The :mod:`cookielib` module defines classes for automatic handling of HTTP
  13. cookies. It is useful for accessing web sites that require small pieces of data
  14. -- :dfn:`cookies` -- to be set on the client machine by an HTTP response from a
  15. web server, and then returned to the server in later HTTP requests.
  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 treated
  19. either as Netscape or RFC 2965 cookies according to the 'policy' in effect.
  20. Note 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
  22. differs substantially from that set out in the original Netscape specification),
  23. including taking note of the ``max-age`` and ``port`` cookie-attributes
  24. introduced with RFC 2965.
  25. .. note::
  26. The various named parameters found in :mailheader:`Set-Cookie` and
  27. :mailheader:`Set-Cookie2` headers (eg. ``domain`` and ``expires``) are
  28. conventionally referred to as :dfn:`attributes`. To distinguish them from
  29. Python attributes, the documentation for this module uses the term
  30. :dfn:`cookie-attribute` instead.
  31. The module defines the following exception:
  32. .. exception:: LoadError
  33. Instances of :class:`FileCookieJar` raise this exception on failure to load
  34. cookies from a file.
  35. .. note::
  36. For backwards-compatibility with Python 2.4 (which raised an :exc:`IOError`),
  37. :exc:`LoadError` is a subclass of :exc:`IOError`.
  38. The following classes are provided:
  39. .. class:: CookieJar(policy=None)
  40. *policy* is an object implementing the :class:`CookiePolicy` interface.
  41. The :class:`CookieJar` class stores HTTP cookies. It extracts cookies from HTTP
  42. requests, and returns them in HTTP responses. :class:`CookieJar` instances
  43. automatically expire contained cookies when necessary. Subclasses are also
  44. responsible for storing and retrieving cookies from a file or database.
  45. .. class:: FileCookieJar(filename, delayload=None, policy=None)
  46. *policy* is an object implementing the :class:`CookiePolicy` interface. For the
  47. other arguments, see the documentation for the corresponding attributes.
  48. A :class:`CookieJar` which can load cookies from, and perhaps save cookies to, a
  49. file on disk. Cookies are **NOT** loaded from the named file until either the
  50. :meth:`load` or :meth:`revert` method is called. Subclasses of this class are
  51. documented in section :ref:`file-cookie-jar-classes`.
  52. .. class:: CookiePolicy()
  53. This class is responsible for deciding whether each cookie should be accepted
  54. from / returned to the server.
  55. .. 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 )
  56. Constructor arguments should be passed as keyword arguments only.
  57. *blocked_domains* is a sequence of domain names that we never accept cookies
  58. from, nor return cookies to. *allowed_domains* if not :const:`None`, this is a
  59. sequence of the only domains for which we accept and return cookies. For all
  60. other arguments, see the documentation for :class:`CookiePolicy` and
  61. :class:`DefaultCookiePolicy` objects.
  62. :class:`DefaultCookiePolicy` implements the standard accept / reject rules for
  63. Netscape and RFC 2965 cookies. By default, RFC 2109 cookies (ie. cookies
  64. received in a :mailheader:`Set-Cookie` header with a version cookie-attribute of
  65. 1) are treated according to the RFC 2965 rules. However, if RFC 2965 handling
  66. is turned off or :attr:`rfc2109_as_netscape` is True, RFC 2109 cookies are
  67. 'downgraded' by the :class:`CookieJar` instance to Netscape cookies, by
  68. setting the :attr:`version` attribute of the :class:`Cookie` instance to 0.
  69. :class:`DefaultCookiePolicy` also provides some parameters to allow some
  70. fine-tuning of policy.
  71. .. class:: Cookie()
  72. This class represents Netscape, RFC 2109 and RFC 2965 cookies. It is not
  73. expected that users of :mod:`cookielib` construct their own :class:`Cookie`
  74. instances. Instead, if necessary, call :meth:`make_cookies` on a
  75. :class:`CookieJar` instance.
  76. .. seealso::
  77. Module :mod:`urllib2`
  78. URL opening with automatic cookie handling.
  79. Module :mod:`Cookie`
  80. HTTP cookie classes, principally useful for server-side code. The
  81. :mod:`cookielib` and :mod:`Cookie` modules do not depend on each other.
  82. http://wwwsearch.sf.net/ClientCookie/
  83. Extensions to this module, including a class for reading Microsoft Internet
  84. Explorer cookies on Windows.
  85. http://wp.netscape.com/newsref/std/cookie_spec.html
  86. The specification of the original Netscape cookie protocol. Though this is
  87. still the dominant protocol, the 'Netscape cookie protocol' implemented by all
  88. the major browsers (and :mod:`cookielib`) only bears a passing resemblance to
  89. the one sketched out in ``cookie_spec.html``.
  90. :rfc:`2109` - HTTP State Management Mechanism
  91. Obsoleted by RFC 2965. Uses :mailheader:`Set-Cookie` with version=1.
  92. :rfc:`2965` - HTTP State Management Mechanism
  93. The Netscape protocol with the bugs fixed. Uses :mailheader:`Set-Cookie2` in
  94. place of :mailheader:`Set-Cookie`. Not widely used.
  95. http://kristol.org/cookie/errata.html
  96. Unfinished errata to RFC 2965.
  97. :rfc:`2964` - Use of HTTP State Management
  98. .. _cookie-jar-objects:
  99. CookieJar and FileCookieJar Objects
  100. -----------------------------------
  101. :class:`CookieJar` objects support the :term:`iterator` protocol for iterating over
  102. contained :class:`Cookie` objects.
  103. :class:`CookieJar` has the following methods:
  104. .. method:: CookieJar.add_cookie_header(request)
  105. Add correct :mailheader:`Cookie` header to *request*.
  106. If policy allows (ie. the :attr:`rfc2965` and :attr:`hide_cookie2` attributes of
  107. the :class:`CookieJar`'s :class:`CookiePolicy` instance are true and false
  108. respectively), the :mailheader:`Cookie2` header is also added when appropriate.
  109. The *request* object (usually a :class:`urllib2.Request` instance) must support
  110. the methods :meth:`get_full_url`, :meth:`get_host`, :meth:`get_type`,
  111. :meth:`unverifiable`, :meth:`get_origin_req_host`, :meth:`has_header`,
  112. :meth:`get_header`, :meth:`header_items`, and :meth:`add_unredirected_header`,as
  113. documented by :mod:`urllib2`.
  114. .. method:: CookieJar.extract_cookies(response, request)
  115. Extract cookies from HTTP *response* and store them in the :class:`CookieJar`,
  116. where allowed by policy.
  117. The :class:`CookieJar` will look for allowable :mailheader:`Set-Cookie` and
  118. :mailheader:`Set-Cookie2` headers in the *response* argument, and store cookies
  119. as appropriate (subject to the :meth:`CookiePolicy.set_ok` method's approval).
  120. The *response* object (usually the result of a call to :meth:`urllib2.urlopen`,
  121. or similar) should support an :meth:`info` method, which returns an object with
  122. a :meth:`getallmatchingheaders` method (usually a :class:`mimetools.Message`
  123. instance).
  124. The *request* object (usually a :class:`urllib2.Request` instance) must support
  125. the methods :meth:`get_full_url`, :meth:`get_host`, :meth:`unverifiable`, and
  126. :meth:`get_origin_req_host`, as documented by :mod:`urllib2`. The request is
  127. used to set default values for cookie-attributes as well as for checking that
  128. the cookie is allowed to be set.
  129. .. method:: CookieJar.set_policy(policy)
  130. Set the :class:`CookiePolicy` instance to be used.
  131. .. method:: CookieJar.make_cookies(response, request)
  132. Return sequence of :class:`Cookie` objects extracted from *response* object.
  133. See the documentation for :meth:`extract_cookies` for the interfaces required of
  134. the *response* and *request* arguments.
  135. .. method:: CookieJar.set_cookie_if_ok(cookie, request)
  136. Set a :class:`Cookie` if policy says it's OK to do so.
  137. .. method:: CookieJar.set_cookie(cookie)
  138. Set a :class:`Cookie`, without checking with policy to see whether or not it
  139. should be set.
  140. .. method:: CookieJar.clear([domain[, path[, name]]])
  141. Clear some cookies.
  142. If invoked without arguments, clear all cookies. If given a single argument,
  143. only cookies belonging to that *domain* will be removed. If given two arguments,
  144. cookies belonging to the specified *domain* and URL *path* are removed. If
  145. given three arguments, then the cookie with the specified *domain*, *path* and
  146. *name* is removed.
  147. Raises :exc:`KeyError` if no matching cookie exists.
  148. .. method:: CookieJar.clear_session_cookies()
  149. Discard all session cookies.
  150. Discards all contained cookies that have a true :attr:`discard` attribute
  151. (usually because they had either no ``max-age`` or ``expires`` cookie-attribute,
  152. or an explicit ``discard`` cookie-attribute). For interactive browsers, the end
  153. of a session usually corresponds to closing the browser window.
  154. Note that the :meth:`save` method won't save session cookies anyway, unless you
  155. ask otherwise by passing a true *ignore_discard* argument.
  156. :class:`FileCookieJar` implements the following additional methods:
  157. .. method:: FileCookieJar.save(filename=None, ignore_discard=False, ignore_expires=False)
  158. Save cookies to a file.
  159. This base class raises :exc:`NotImplementedError`. Subclasses may leave this
  160. method unimplemented.
  161. *filename* is the name of file in which to save cookies. If *filename* is not
  162. specified, :attr:`self.filename` is used (whose default is the value passed to
  163. the constructor, if any); if :attr:`self.filename` is :const:`None`,
  164. :exc:`ValueError` is raised.
  165. *ignore_discard*: save even cookies set to be discarded. *ignore_expires*: save
  166. even cookies that have expired
  167. The file is overwritten if it already exists, thus wiping all the cookies it
  168. contains. Saved cookies can be restored later using the :meth:`load` or
  169. :meth:`revert` methods.
  170. .. method:: FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False)
  171. Load cookies from a file.
  172. Old cookies are kept unless overwritten by newly loaded ones.
  173. Arguments are as for :meth:`save`.
  174. The named file must be in the format understood by the class, or
  175. :exc:`LoadError` will be raised. Also, :exc:`IOError` may be raised, for
  176. example if the file does not exist.
  177. .. note::
  178. For backwards-compatibility with Python 2.4 (which raised an :exc:`IOError`),
  179. :exc:`LoadError` is a subclass of :exc:`IOError`.
  180. .. method:: FileCookieJar.revert(filename=None, ignore_discard=False, ignore_expires=False)
  181. Clear all cookies and reload cookies from a saved file.
  182. :meth:`revert` can raise the same exceptions as :meth:`load`. If there is a
  183. failure, the object's state will not be altered.
  184. :class:`FileCookieJar` instances have the following public attributes:
  185. .. attribute:: FileCookieJar.filename
  186. Filename of default file in which to keep cookies. This attribute may be
  187. assigned to.
  188. .. attribute:: FileCookieJar.delayload
  189. If true, load cookies lazily from disk. This attribute should not be assigned
  190. to. This is only a hint, since this only affects performance, not behaviour
  191. (unless the cookies on disk are changing). A :class:`CookieJar` object may
  192. ignore it. None of the :class:`FileCookieJar` classes included in the standard
  193. library lazily loads cookies.
  194. .. _file-cookie-jar-classes:
  195. FileCookieJar subclasses and co-operation with web browsers
  196. -----------------------------------------------------------
  197. The following :class:`CookieJar` subclasses are provided for reading and writing
  198. . Further :class:`CookieJar` subclasses, including one that reads Microsoft
  199. Internet Explorer cookies, are available at
  200. http://wwwsearch.sf.net/ClientCookie/.
  201. .. class:: MozillaCookieJar(filename, delayload=None, policy=None)
  202. A :class:`FileCookieJar` that can load from and save cookies to disk in the
  203. Mozilla ``cookies.txt`` file format (which is also used by the Lynx and Netscape
  204. browsers).
  205. .. note::
  206. Version 3 of the Firefox web browser no longer writes cookies in the
  207. ``cookies.txt`` file format.
  208. .. note::
  209. This loses information about RFC 2965 cookies, and also about newer or
  210. non-standard cookie-attributes such as ``port``.
  211. .. warning::
  212. Back up your cookies before saving if you have cookies whose loss / corruption
  213. would be inconvenient (there are some subtleties which may lead to slight
  214. changes in the file over a load / save round-trip).
  215. Also note that cookies saved while Mozilla is running will get clobbered by
  216. Mozilla.
  217. .. class:: LWPCookieJar(filename, delayload=None, policy=None)
  218. A :class:`FileCookieJar` that can load from and save cookies to disk in format
  219. compatible with the libwww-perl library's ``Set-Cookie3`` file format. This is
  220. convenient if you want to store cookies in a human-readable file.
  221. .. _cookie-policy-objects:
  222. CookiePolicy Objects
  223. --------------------
  224. Objects implementing the :class:`CookiePolicy` interface have the following
  225. methods:
  226. .. method:: CookiePolicy.set_ok(cookie, request)
  227. Return boolean value indicating whether cookie should be accepted from server.
  228. *cookie* is a :class:`cookielib.Cookie` instance. *request* is an object
  229. implementing the interface defined by the documentation for
  230. :meth:`CookieJar.extract_cookies`.
  231. .. method:: CookiePolicy.return_ok(cookie, request)
  232. Return boolean value indicating whether cookie should be returned to server.
  233. *cookie* is a :class:`cookielib.Cookie` instance. *request* is an object
  234. implementing the interface defined by the documentation for
  235. :meth:`CookieJar.add_cookie_header`.
  236. .. method:: CookiePolicy.domain_return_ok(domain, request)
  237. Return false if cookies should not be returned, given cookie domain.
  238. This method is an optimization. It removes the need for checking every cookie
  239. with a particular domain (which might involve reading many files). Returning
  240. true from :meth:`domain_return_ok` and :meth:`path_return_ok` leaves all the
  241. work to :meth:`return_ok`.
  242. If :meth:`domain_return_ok` returns true for the cookie domain,
  243. :meth:`path_return_ok` is called for the cookie path. Otherwise,
  244. :meth:`path_return_ok` and :meth:`return_ok` are never called for that cookie
  245. domain. If :meth:`path_return_ok` returns true, :meth:`return_ok` is called
  246. with the :class:`Cookie` object itself for a full check. Otherwise,
  247. :meth:`return_ok` is never called for that cookie path.
  248. Note that :meth:`domain_return_ok` is called for every *cookie* domain, not just
  249. for the *request* domain. For example, the function might be called with both
  250. ``".example.com"`` and ``"www.example.com"`` if the request domain is
  251. ``"www.example.com"``. The same goes for :meth:`path_return_ok`.
  252. The *request* argument is as documented for :meth:`return_ok`.
  253. .. method:: CookiePolicy.path_return_ok(path, request)
  254. Return false if cookies should not be returned, given cookie path.
  255. See the documentation for :meth:`domain_return_ok`.
  256. In addition to implementing the methods above, implementations of the
  257. :class:`CookiePolicy` interface must also supply the following attributes,
  258. indicating which protocols should be used, and how. All of these attributes may
  259. be assigned to.
  260. .. attribute:: CookiePolicy.netscape
  261. Implement Netscape protocol.
  262. .. attribute:: CookiePolicy.rfc2965
  263. Implement RFC 2965 protocol.
  264. .. attribute:: CookiePolicy.hide_cookie2
  265. Don't add :mailheader:`Cookie2` header to requests (the presence of this header
  266. indicates to the server that we understand RFC 2965 cookies).
  267. The most useful way to define a :class:`CookiePolicy` class is by subclassing
  268. from :class:`DefaultCookiePolicy` and overriding some or all of the methods
  269. above. :class:`CookiePolicy` itself may be used as a 'null policy' to allow
  270. setting and receiving any and all cookies (this is unlikely to be useful).
  271. .. _default-cookie-policy-objects:
  272. DefaultCookiePolicy Objects
  273. ---------------------------
  274. Implements the standard rules for accepting and returning cookies.
  275. Both RFC 2965 and Netscape cookies are covered. RFC 2965 handling is switched
  276. off by default.
  277. The easiest way to provide your own policy is to override this class and call
  278. its methods in your overridden implementations before adding your own additional
  279. checks::
  280. import cookielib
  281. class MyCookiePolicy(cookielib.DefaultCookiePolicy):
  282. def set_ok(self, cookie, request):
  283. if not cookielib.DefaultCookiePolicy.set_ok(self, cookie, request):
  284. return False
  285. if i_dont_want_to_store_this_cookie(cookie):
  286. return False
  287. return True
  288. In addition to the features required to implement the :class:`CookiePolicy`
  289. interface, this class allows you to block and allow domains from setting and
  290. receiving cookies. There are also some strictness switches that allow you to
  291. tighten up the rather loose Netscape protocol rules a little bit (at the cost of
  292. blocking some benign cookies).
  293. A domain blacklist and whitelist is provided (both off by default). Only domains
  294. not in the blacklist and present in the whitelist (if the whitelist is active)
  295. participate in cookie setting and returning. Use the *blocked_domains*
  296. constructor argument, and :meth:`blocked_domains` and
  297. :meth:`set_blocked_domains` methods (and the corresponding argument and methods
  298. for *allowed_domains*). If you set a whitelist, you can turn it off again by
  299. setting it to :const:`None`.
  300. Domains in block or allow lists that do not start with a dot must equal the
  301. cookie domain to be matched. For example, ``"example.com"`` matches a blacklist
  302. entry of ``"example.com"``, but ``"www.example.com"`` does not. Domains that do
  303. start with a dot are matched by more specific domains too. For example, both
  304. ``"www.example.com"`` and ``"www.coyote.example.com"`` match ``".example.com"``
  305. (but ``"example.com"`` itself does not). IP addresses are an exception, and
  306. must match exactly. For example, if blocked_domains contains ``"192.168.1.2"``
  307. and ``".168.1.2"``, 192.168.1.2 is blocked, but 193.168.1.2 is not.
  308. :class:`DefaultCookiePolicy` implements the following additional methods:
  309. .. method:: DefaultCookiePolicy.blocked_domains()
  310. Return the sequence of blocked domains (as a tuple).
  311. .. method:: DefaultCookiePolicy.set_blocked_domains(blocked_domains)
  312. Set the sequence of blocked domains.
  313. .. method:: DefaultCookiePolicy.is_blocked(domain)
  314. Return whether *domain* is on the blacklist for setting or receiving cookies.
  315. .. method:: DefaultCookiePolicy.allowed_domains()
  316. Return :const:`None`, or the sequence of allowed domains (as a tuple).
  317. .. method:: DefaultCookiePolicy.set_allowed_domains(allowed_domains)
  318. Set the sequence of allowed domains, or :const:`None`.
  319. .. method:: DefaultCookiePolicy.is_not_allowed(domain)
  320. Return whether *domain* is not on the whitelist for setting or receiving
  321. cookies.
  322. :class:`DefaultCookiePolicy` instances have the following attributes, which are
  323. all initialised from the constructor arguments of the same name, and which may
  324. all be assigned to.
  325. .. attribute:: DefaultCookiePolicy.rfc2109_as_netscape
  326. If true, request that the :class:`CookieJar` instance downgrade RFC 2109 cookies
  327. (ie. cookies received in a :mailheader:`Set-Cookie` header with a version
  328. cookie-attribute of 1) to Netscape cookies by setting the version attribute of
  329. the :class:`Cookie` instance to 0. The default value is :const:`None`, in which
  330. case RFC 2109 cookies are downgraded if and only if RFC 2965 handling is turned
  331. off. Therefore, RFC 2109 cookies are downgraded by default.
  332. .. versionadded:: 2.5
  333. General strictness switches:
  334. .. attribute:: DefaultCookiePolicy.strict_domain
  335. Don't allow sites to set two-component domains with country-code top-level
  336. domains like ``.co.uk``, ``.gov.uk``, ``.co.nz``.etc. This is far from perfect
  337. and isn't guaranteed to work!
  338. RFC 2965 protocol strictness switches:
  339. .. attribute:: DefaultCookiePolicy.strict_rfc2965_unverifiable
  340. Follow RFC 2965 rules on unverifiable transactions (usually, an unverifiable
  341. transaction is one resulting from a redirect or a request for an image hosted on
  342. another site). If this is false, cookies are *never* blocked on the basis of
  343. verifiability
  344. Netscape protocol strictness switches:
  345. .. attribute:: DefaultCookiePolicy.strict_ns_unverifiable
  346. apply RFC 2965 rules on unverifiable transactions even to Netscape cookies
  347. .. attribute:: DefaultCookiePolicy.strict_ns_domain
  348. Flags indicating how strict to be with domain-matching rules for Netscape
  349. cookies. See below for acceptable values.
  350. .. attribute:: DefaultCookiePolicy.strict_ns_set_initial_dollar
  351. Ignore cookies in Set-Cookie: headers that have names starting with ``'$'``.
  352. .. attribute:: DefaultCookiePolicy.strict_ns_set_path
  353. Don't allow setting cookies whose path doesn't path-match request URI.
  354. :attr:`strict_ns_domain` is a collection of flags. Its value is constructed by
  355. or-ing together (for example, ``DomainStrictNoDots|DomainStrictNonDomain`` means
  356. both flags are set).
  357. .. attribute:: DefaultCookiePolicy.DomainStrictNoDots
  358. When setting cookies, the 'host prefix' must not contain a dot (eg.
  359. ``www.foo.bar.com`` can't set a cookie for ``.bar.com``, because ``www.foo``
  360. contains a dot).
  361. .. attribute:: DefaultCookiePolicy.DomainStrictNonDomain
  362. Cookies that did not explicitly specify a ``domain`` cookie-attribute can only
  363. be returned to a domain equal to the domain that set the cookie (eg.
  364. ``spam.example.com`` won't be returned cookies from ``example.com`` that had no
  365. ``domain`` cookie-attribute).
  366. .. attribute:: DefaultCookiePolicy.DomainRFC2965Match
  367. When setting cookies, require a full RFC 2965 domain-match.
  368. The following attributes are provided for convenience, and are the most useful
  369. combinations of the above flags:
  370. .. attribute:: DefaultCookiePolicy.DomainLiberal
  371. Equivalent to 0 (ie. all of the above Netscape domain strictness flags switched
  372. off).
  373. .. attribute:: DefaultCookiePolicy.DomainStrict
  374. Equivalent to ``DomainStrictNoDots|DomainStrictNonDomain``.
  375. .. _cookielib-cookie-objects:
  376. Cookie Objects
  377. --------------
  378. :class:`Cookie` instances have Python attributes roughly corresponding to the
  379. standard cookie-attributes specified in the various cookie standards. The
  380. correspondence is not one-to-one, because there are complicated rules for
  381. assigning default values, because the ``max-age`` and ``expires``
  382. cookie-attributes contain equivalent information, and because RFC 2109 cookies
  383. may be 'downgraded' by :mod:`cookielib` from version 1 to version 0 (Netscape)
  384. cookies.
  385. Assignment to these attributes should not be necessary other than in rare
  386. circumstances in a :class:`CookiePolicy` method. The class does not enforce
  387. internal consistency, so you should know what you're doing if you do that.
  388. .. attribute:: Cookie.version
  389. Integer or :const:`None`. Netscape cookies have :attr:`version` 0. RFC 2965 and
  390. RFC 2109 cookies have a ``version`` cookie-attribute of 1. However, note that
  391. :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in which
  392. case :attr:`version` is 0.
  393. .. attribute:: Cookie.name
  394. Cookie name (a string).
  395. .. attribute:: Cookie.value
  396. Cookie value (a string), or :const:`None`.
  397. .. attribute:: Cookie.port
  398. String representing a port or a set of ports (eg. '80', or '80,8080'), or
  399. :const:`None`.
  400. .. attribute:: Cookie.path
  401. Cookie path (a string, eg. ``'/acme/rocket_launchers'``).
  402. .. attribute:: Cookie.secure
  403. True if cookie should only be returned over a secure connection.
  404. .. attribute:: Cookie.expires
  405. Integer expiry date in seconds since epoch, or :const:`None`. See also the
  406. :meth:`is_expired` method.
  407. .. attribute:: Cookie.discard
  408. True if this is a session cookie.
  409. .. attribute:: Cookie.comment
  410. String comment from the server explaining the function of this cookie, or
  411. :const:`None`.
  412. .. attribute:: Cookie.comment_url
  413. URL linking to a comment from the server explaining the function of this cookie,
  414. or :const:`None`.
  415. .. attribute:: Cookie.rfc2109
  416. True if this cookie was received as an RFC 2109 cookie (ie. the cookie
  417. arrived in a :mailheader:`Set-Cookie` header, and the value of the Version
  418. cookie-attribute in that header was 1). This attribute is provided because
  419. :mod:`cookielib` may 'downgrade' RFC 2109 cookies to Netscape cookies, in
  420. which case :attr:`version` is 0.
  421. .. versionadded:: 2.5
  422. .. attribute:: Cookie.port_specified
  423. True if a port or set of ports was explicitly specified by the server (in the
  424. :mailheader:`Set-Cookie` / :mailheader:`Set-Cookie2` header).
  425. .. attribute:: Cookie.domain_specified
  426. True if a domain was explicitly specified by the server.
  427. .. attribute:: Cookie.domain_initial_dot
  428. True if the domain explicitly specified by the server began with a dot
  429. (``'.'``).
  430. Cookies may have additional non-standard cookie-attributes. These may be
  431. accessed using the following methods:
  432. .. method:: Cookie.has_nonstandard_attr(name)
  433. Return true if cookie has the named cookie-attribute.
  434. .. method:: Cookie.get_nonstandard_attr(name, default=None)
  435. If cookie has the named cookie-attribute, return its value. Otherwise, return
  436. *default*.
  437. .. method:: Cookie.set_nonstandard_attr(name, value)
  438. Set the value of the named cookie-attribute.
  439. The :class:`Cookie` class also defines the following method:
  440. .. method:: Cookie.is_expired([now=None])
  441. True if cookie has passed the time at which the server requested it should
  442. expire. If *now* is given (in seconds since the epoch), return whether the
  443. cookie has expired at the specified time.
  444. .. _cookielib-examples:
  445. Examples
  446. --------
  447. The first example shows the most common usage of :mod:`cookielib`::
  448. import cookielib, urllib2
  449. cj = cookielib.CookieJar()
  450. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  451. r = opener.open("http://example.com/")
  452. This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx
  453. cookies (assumes Unix/Netscape convention for location of the cookies file)::
  454. import os, cookielib, urllib2
  455. cj = cookielib.MozillaCookieJar()
  456. cj.load(os.path.join(os.environ["HOME"], ".netscape/cookies.txt"))
  457. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  458. r = opener.open("http://example.com/")
  459. The next example illustrates the use of :class:`DefaultCookiePolicy`. Turn on
  460. RFC 2965 cookies, be more strict about domains when setting and returning
  461. Netscape cookies, and block some domains from setting cookies or having them
  462. returned::
  463. import urllib2
  464. from cookielib import CookieJar, DefaultCookiePolicy
  465. policy = DefaultCookiePolicy(
  466. rfc2965=True, strict_ns_domain=DefaultCookiePolicy.DomainStrict,
  467. blocked_domains=["ads.net", ".ads.net"])
  468. cj = CookieJar(policy)
  469. opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cj))
  470. r = opener.open("http://example.com/")