18.22.3 CookiePolicy Objects

##
18.22.3 CookiePolicy Objects

Objects implementing the `CookiePolicy` interface have the following methods:

`set_ok`( | cookie, request)

  Return boolean value indicating whether cookie should be accepted from server.

  cookie is a `cookielib.Cookie` instance. request is an object implementing the interface defined by the documentation for `CookieJar.extract_cookies()`.

`return_ok`( | cookie, request)

  Return boolean value indicating whether cookie should be returned to server.

  cookie is a `cookielib.Cookie` instance. request is an object implementing the interface defined by the documentation for `CookieJar.add_cookie_header()`.

`domain_return_ok`( | domain, request)

  Return false if cookies should not be returned, given cookie domain.

  This method is an optimization. It removes the need for checking every cookie with a particular domain (which might involve reading many files). Returning true from `domain_return_ok()` and `path_return_ok()` leaves all the work to `return_ok()`.

  If `domain_return_ok()` returns true for the cookie domain, `path_return_ok()` is called for the cookie path. Otherwise, `path_return_ok()` and `return_ok()` are never called for that cookie domain. If `path_return_ok()` returns true, `return_ok()` is called with the `Cookie` object itself for a full check. Otherwise, `return_ok()` is never called for that cookie path.

  Note that `domain_return_ok()` is called for every cookie domain, not just for the request domain. For example, the function might be called with both `".example.com"` and `"www.example.com"` if the request domain is `"www.example.com"`. The same goes for `path_return_ok()`.

  The request argument is as documented for `return_ok()`.

`path_return_ok`( | path, request)

  Return false if cookies should not be returned, given cookie path.

  See the documentation for `domain_return_ok()`.

In addition to implementing the methods above, implementations of the `CookiePolicy` interface must also supply the following attributes, indicating which protocols should be used, and how. All of these attributes may be assigned to.

`netscape`
  Implement Netscape protocol.

`rfc2965`
  Implement RFC 2965 protocol.

`hide_cookie2`
  Don't add Cookie2: header to requests (the presence of this header indicates to the server that we understand RFC 2965 cookies).

The most useful way to define a `CookiePolicy` class is by subclassing from `DefaultCookiePolicy` and overriding some or all of the methods above. `CookiePolicy` itself may be used as a 'null policy' to allow setting and receiving any and all cookies (this is unlikely to be useful).