DefaultCookiePolicy 对象
¶
Implements the standard rules for accepting and returning cookies.
Both
RFC 2965
and Netscape cookies are covered. RFC 2965 handling is switched off by default.
The easiest way to provide your own policy is to override this class and call its methods in your overridden implementations before adding your own additional checks:
import http.cookiejar
class MyCookiePolicy(http.cookiejar.DefaultCookiePolicy):
def set_ok(self, cookie, request):
if not http.cookiejar.DefaultCookiePolicy.set_ok(self, cookie, request):
return False
if i_dont_want_to_store_this_cookie(cookie):
return False
return True
In addition to the features required to implement the
CookiePolicy
interface, this class allows you to block and allow domains from setting and receiving cookies. There are also some strictness switches that allow you to tighten up the rather loose Netscape protocol rules a little bit (at the cost of blocking some benign cookies).
A domain blocklist and allowlist is provided (both off by default). Only domains not in the blocklist and present in the allowlist (if the allowlist is active) participate in cookie setting and returning. Use the
blocked_domains
constructor argument, and
blocked_domains()
and
set_blocked_domains()
methods (and the corresponding argument and methods for
allowed_domains
). If you set an allowlist, you can turn it off again by setting it to
None
.
Domains in block or allow lists that do not start with a dot must equal the cookie domain to be matched. For example,
"example.com"
matches a blocklist entry of
"example.com"
,但
"www.example.com"
does not. Domains that do start with a dot are matched by more specific domains too. For example, both
"www.example.com"
and
"www.coyote.example.com"
match
".example.com"
(但
"example.com"
itself does not). IP addresses are an exception, and must match exactly. For example, if blocked_domains contains
"192.168.1.2"
and
".168.1.2"
, 192.168.1.2 is blocked, but 193.168.1.2 is not.
DefaultCookiePolicy
实现下列额外方法:
-
DefaultCookiePolicy.
blocked_domains
(
)
¶
-
Return the sequence of blocked domains (as a tuple).
-
DefaultCookiePolicy.
set_blocked_domains
(
blocked_domains
)
¶
-
Set the sequence of blocked domains.
-
DefaultCookiePolicy.
is_blocked
(
domain
)
¶
-
返回
True
if
domain
is on the blocklist for setting or receiving cookies.
-
DefaultCookiePolicy.
allowed_domains
(
)
¶
-
返回
None
, or the sequence of allowed domains (as a tuple).
-
DefaultCookiePolicy.
set_allowed_domains
(
allowed_domains
)
¶
-
Set the sequence of allowed domains, or
None
.
-
DefaultCookiePolicy.
is_not_allowed
(
domain
)
¶
-
返回
True
if
domain
is not on the allowlist for setting or receiving cookies.
DefaultCookiePolicy
instances have the following attributes, which are all initialised from the constructor arguments of the same name, and which may all be assigned to.
-
DefaultCookiePolicy.
rfc2109_as_netscape
¶
-
若 true,请求
CookieJar
实例降级
RFC 2109
cookies (ie. cookies received in a
header with a version cookie-attribute of 1) to Netscape cookies by setting the version attribute of the
Cookie
instance to 0. The default value is
None
, in which case RFC 2109 cookies are downgraded if and only if
RFC 2965
handling is turned off. Therefore, RFC 2109 cookies are downgraded by default.
一般严格开关:
-
DefaultCookiePolicy.
strict_domain
¶
-
Don’t allow sites to set two-component domains with country-code top-level domains like
.co.uk
,
.gov.uk
,
.co.nz
.etc. This is far from perfect and isn’t guaranteed to work!
RFC 2965
protocol strictness switches:
-
DefaultCookiePolicy.
strict_rfc2965_unverifiable
¶
-
Follow
RFC 2965
rules on unverifiable transactions (usually, an unverifiable transaction is one resulting from a redirect or a request for an image hosted on another site). If this is false, cookies are
never
blocked on the basis of verifiability
Netscape protocol strictness switches:
-
DefaultCookiePolicy.
strict_ns_unverifiable
¶
-
应用
RFC 2965
rules on unverifiable transactions even to Netscape cookies.
-
DefaultCookiePolicy.
strict_ns_domain
¶
-
Flags indicating how strict to be with domain-matching rules for Netscape cookies. See below for acceptable values.
-
DefaultCookiePolicy.
strict_ns_set_initial_dollar
¶
-
Ignore cookies in Set-Cookie: headers that have names starting with
'$'
.
-
DefaultCookiePolicy.
strict_ns_set_path
¶
-
Don’t allow setting cookies whose path doesn’t path-match request URI.
strict_ns_domain
is a collection of flags. Its value is constructed by or-ing together (for example,
DomainStrictNoDots|DomainStrictNonDomain
means both flags are set).
-
DefaultCookiePolicy.
DomainStrictNoDots
¶
-
When setting cookies, the ‘host prefix’ must not contain a dot (eg.
www.foo.bar.com
can’t set a cookie for
.bar.com
,因为
www.foo
contains a dot).
-
DefaultCookiePolicy.
DomainStrictNonDomain
¶
-
Cookies that did not explicitly specify a
domain
cookie-attribute can only be returned to a domain equal to the domain that set the cookie (eg.
spam.example.com
won’t be returned cookies from
example.com
that had no
domain
cookie-attribute).
-
DefaultCookiePolicy.
DomainRFC2965Match
¶
-
When setting cookies, require a full
RFC 2965
domain-match.
The following attributes are provided for convenience, and are the most useful combinations of the above flags:
-
DefaultCookiePolicy.
DomainLiberal
¶
-
Equivalent to 0 (ie. all of the above Netscape domain strictness flags switched off).
-
DefaultCookiePolicy.
DomainStrict
¶
-
相当于
DomainStrictNoDots|DomainStrictNonDomain
.
Cookie 对象
¶
Cookie
instances have Python attributes roughly corresponding to the standard cookie-attributes specified in the various cookie standards. The correspondence is not one-to-one, because there are complicated rules for assigning default values, because the
max-age
and
expires
cookie-attributes contain equivalent information, and because
RFC 2109
cookies may be ‘downgraded’ by
http.cookiejar
from version 1 to version 0 (Netscape) cookies.
Assignment to these attributes should not be necessary other than in rare circumstances in a
CookiePolicy
method. The class does not enforce internal consistency, so you should know what you’re doing if you do that.
-
Cookie.
version
¶
-
整数或
None
. Netscape cookies have
version
0.
RFC 2965
and
RFC 2109
cookies have a
version
cookie-attribute of 1. However, note that
http.cookiejar
may ‘downgrade’ RFC 2109 cookies to Netscape cookies, in which case
version
为 0。
-
Cookie.
名称
¶
-
Cookie 名称 (字符串)。
-
Cookie.
值
¶
-
Cookie 值 (字符串),或
None
.
-
Cookie.
port
¶
-
String representing a port or a set of ports (eg. ‘80’, or ‘80,8080’), or
None
.
-
Cookie.
domain
¶
-
Cookie domain (a string).
-
Cookie.
path
¶
-
Cookie 路径 (字符串,如
'/acme/rocket_launchers'
).
-
Cookie.
secure
¶
-
True
if cookie should only be returned over a secure connection.
-
Cookie.
expires
¶
-
Integer expiry date in seconds since epoch, or
None
。另请参阅
is_expired()
方法。
-
Cookie.
discard
¶
-
True
若这是会话 Cookie。
-
String comment from the server explaining the function of this cookie, or
None
.
-
URL linking to a comment from the server explaining the function of this cookie, or
None
.
-
Cookie.
rfc2109
¶
-
True
if this cookie was received as an
RFC 2109
cookie (ie. the cookie arrived in a
header, and the value of the Version cookie-attribute in that header was 1). This attribute is provided because
http.cookiejar
may ‘downgrade’ RFC 2109 cookies to Netscape cookies, in which case
version
为 0。
-
Cookie.
port_specified
¶
-
True
if a port or set of ports was explicitly specified by the server (in the
/
头)。
-
Cookie.
domain_specified
¶
-
True
if a domain was explicitly specified by the server.
-
Cookie.
domain_initial_dot
¶
-
True
if the domain explicitly specified by the server began with a dot (
'.'
).
Cookies may have additional non-standard cookie-attributes. These may be accessed using the following methods:
-
Cookie.
has_nonstandard_attr
(
名称
)
¶
-
返回
True
if cookie has the named cookie-attribute.
-
Cookie.
get_nonstandard_attr
(
名称
,
default
=
None
)
¶
-
If cookie has the named cookie-attribute, return its value. Otherwise, return
default
.
-
Cookie.
set_nonstandard_attr
(
名称
,
值
)
¶
-
Set the value of the named cookie-attribute.
The
Cookie
class also defines the following method:
-
Cookie.
is_expired
(
now
=
None
)
¶
-
True
if cookie has passed the time at which the server requested it should expire. If
now
is given (in seconds since the epoch), return whether the cookie has expired at the specified time.
范例
¶
The first example shows the most common usage of
http.cookiejar
:
import http.cookiejar, urllib.request
cj = http.cookiejar.CookieJar()
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
This example illustrates how to open a URL using your Netscape, Mozilla, or Lynx cookies (assumes Unix/Netscape convention for location of the cookies file):
import os, http.cookiejar, urllib.request
cj = http.cookiejar.MozillaCookieJar()
cj.load(os.path.join(os.path.expanduser("~"), ".netscape", "cookies.txt"))
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")
The next example illustrates the use of
DefaultCookiePolicy
. Turn on
RFC 2965
cookies, be more strict about domains when setting and returning Netscape cookies, and block some domains from setting cookies or having them returned:
import urllib.request
from http.cookiejar import CookieJar, DefaultCookiePolicy
policy = DefaultCookiePolicy(
rfc2965=True, strict_ns_domain=Policy.DomainStrict,
blocked_domains=["ads.net", ".ads.net"])
cj = CookieJar(policy)
opener = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(cj))
r = opener.open("http://example.com/")