http.cookiejar --- HTTP 用戶端的 Cookie 處理

原始碼:Lib/http/cookiejar.py


http.cookiejar 模組定義了自動處理 HTTP cookie 的類別。當需要存取小量資料 —— cookies —— 的網站時會非常有用。這些資料會依據網頁伺服器的 HTTP 回應來設置於用戶端機器,並在之後的請求中被回傳到伺服器。

一般的 Netscape cookie 協定和 RFC 2965 定義的 cookie 協定都會被處理。RFC 2965 的處理預設是關閉的。RFC 2109 cookie 會被剖析為 Netscape cookie,然後根據有生效的「策略」來被看作為 Netscape 或 RFC 2965 cookie。http.cookiejar 會嘗試遵循實際上的 Netscape cookie 協定(與原始的 Netscape 規格中的協定有很大的不同),包括 RFC 2965 所引進的 max-ageport cookie 屬性。

備註

The various named parameters found in Set-Cookie and Set-Cookie2 headers (for example, domain and expires) are conventionally referred to as attributes. To distinguish them from Python attributes, the documentation for this module uses the term cookie-attribute instead.

模組定義了以下例外:

exception http.cookiejar.LoadError

當從檔案載入 cookies 失敗時,FileCookieJar 的實例會引發這個例外。LoadErrorOSError 的子類別。

在 3.3 版的變更: LoadError 以前是 IOError 的子型別,現在是 OSError 的別名。

這個模組提供了以下類別:

class http.cookiejar.CookieJar(policy=None)

policy 是實作了 CookiePolicy 介面的一個物件。

CookieJar 類別會儲存 HTTP cookies。它會從 HTTP 請求中抽取出 cookies,並在 HTTP 回應中將它們回傳。CookieJar 實例會在必要時自動使包含的 cookies 過期。它的子類別也負責從檔案或資料庫中儲存和擷取 cookies。

class http.cookiejar.FileCookieJar(filename=None, delayload=None, policy=None)

policy 是實作了 CookiePolicy 介面的一個物件。至於其他引數,請參閱對應屬性的說明文件。

一個可以從磁碟上的檔案載入 Cookie,也可以儲存 Cookie 到磁碟上檔案的 CookieJar。在 load()revert() 方法被呼叫之前,Cookie 並不會從指定的檔案載入。這個類別的子類別有記載於 FileCookieJar 子類別及與網頁瀏覽器的合作 章節。

這個類別不應該直接初始化 - 請使用下面的子類別代替。

在 3.8 版的變更: filename 參數支援傳入一個 path-like object

class http.cookiejar.CookiePolicy

此類別負責決定是否應從伺服器接受 / 回傳每個 cookie。

class http.cookiejar.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, secure_protocols=('https', 'wss'))

Constructor arguments should be passed as keyword arguments only. blocked_domains is a sequence of domain names that we never accept cookies from, nor return cookies to. allowed_domains if not None, this is a sequence of the only domains for which we accept and return cookies. secure_protocols is a sequence of protocols for which secure cookies can be added to. By default https and wss (secure websocket) are considered secure protocols. For all other arguments, see the documentation for CookiePolicy and DefaultCookiePolicy objects.

DefaultCookiePolicy implements the standard accept / reject rules for Netscape and RFC 2965 cookies. By default, RFC 2109 cookies (that is, cookies received in a Set-Cookie header with a version cookie-attribute of 1) are treated according to the RFC 2965 rules. However, if RFC 2965 handling is turned off or rfc2109_as_netscape is True, RFC 2109 cookies are 'downgraded' by the CookieJar instance to Netscape cookies, by setting the version attribute of the Cookie instance to 0. DefaultCookiePolicy also provides some parameters to allow some fine-tuning of policy.

class http.cookiejar.Cookie

This class represents Netscape, RFC 2109 and RFC 2965 cookies. It is not expected that users of http.cookiejar construct their own Cookie instances. Instead, if necessary, call make_cookies() on a CookieJar instance.

也參考

urllib.request 模組

URL 打開時會自動處理 cookie。

http.cookies 模組

HTTP cookie 類別,主要用於伺服器端程式碼。 http.cookiejarhttp.cookies 模組不互相依賴。

https://curl.se/rfc/cookie_spec.html

原始 Netscape cookie 協定的規範。雖然這仍是主流協定,但所有主要瀏覽器(以及 http.cookiejar)實作的「Netscape cookie 協定」與 cookie_spec.html 中實作的協定只有一點相似之處。

RFC 2109 - HTTP 狀態管理機制

RFC 2965 所取代,會使用 Set-Cookie 設定 version=1。

RFC 2965 - HTTP 狀態管理機制

有錯誤修正的 Netscape 通訊協定。使用 Set-Cookie2 取代 Set-Cookie。未被廣泛使用。

https://kristol.org/cookie/errata.html

未完成的 RFC 2965 勘誤表。

RFC 2964 - HTTP 狀態管理使用方法

CookieJar and FileCookieJar objects

CookieJar 物件支援 iterator 協定來遍歷包含的 Cookie 物件。

CookieJar 擁有以下方法:

將正確的 Cookie 標頭加入 request

If policy allows (that is, the rfc2965 and hide_cookie2 attributes of the CookieJar's CookiePolicy instance are true and false respectively), the Cookie2 header is also added when appropriate.

The request object (usually a urllib.request.Request instance) must support the methods get_full_url(), has_header(), get_header(), header_items(), add_unredirected_header() and the attributes host, type, unverifiable and origin_req_host as documented by urllib.request.

在 3.3 版的變更: request object needs origin_req_host attribute. Dependency on a deprecated method get_origin_req_host() has been removed.

CookieJar.extract_cookies(response, request)

在策略允許的情況下,從 HTTP response 抽取出 cookies 並儲存到 CookieJar 中。

CookieJar 會在 response 引數中尋找允許的 Set-CookieSet-Cookie2 標頭,並視情況儲存 cookies(需經 CookiePolicy.set_ok() 方法的檢測)。

The response object (usually the result of a call to urllib.request.urlopen(), or similar) should support an info() method, which returns an email.message.Message instance.

The request object (usually a urllib.request.Request instance) must support the method get_full_url() and the attributes host, unverifiable and origin_req_host, as documented by urllib.request. The request is used to set default values for cookie-attributes as well as for checking that the cookie is allowed to be set.

在 3.3 版的變更: request object needs origin_req_host attribute. Dependency on a deprecated method get_origin_req_host() has been removed.

CookieJar.set_policy(policy)

設定要使用的 CookiePolicy 實例。

CookieJar.make_cookies(response, request)

回傳從 response 物件抽取出的 Cookie 物件序列。

有關 responserequest 引數所需的介面,請參閱 extract_cookies() 的說明檔案。

如果策略允許這麼做,設定 Cookie

設定一個 Cookie,不經過策略檢查。

CookieJar.clear([domain[, path[, name]]])

清除一些 cookies。

如果不帶引數地叫用,則清除所有 cookies。如果給定單一引數,則只移除屬於該 domain 的 cookies。如果給定兩個引數,則會移除屬於指定 domain 和 URL path 的 cookie。 如果給定三個引數,則會移除指定 domainpathname 的 cookie。

如果沒有符合的 cookie 存在,則引發 KeyError

CookieJar.clear_session_cookies()

刪除所有 session cookies。

Discards all contained cookies that have a true discard attribute (usually because they had either no max-age or expires cookie-attribute, or an explicit discard cookie-attribute). For interactive browsers, the end of a session usually corresponds to closing the browser window.

Note that the save() method won't save session cookies anyway, unless you ask otherwise by passing a true ignore_discard argument.

FileCookieJar 實例有下列附加方法:

FileCookieJar.save(filename=None, ignore_discard=False, ignore_expires=False)

將 cookies 儲存到檔案中。

這個基底類別會產生 NotImplementedError。子類別可以不實作此方法。

filename is the name of file in which to save cookies. If filename is not specified, self.filename is used (whose default is the value passed to the constructor, if any); if self.filename is None, ValueError is raised.

ignore_discard: 即使設定為捨棄的 cookies 也會儲存。ignore_expires: 保存過期的 cookie

如果檔案已經存在,則會被覆寫,因此會抹除其中包含的所有 cookies。 儲存的 cookies 可以稍後使用 load()revert() 方法還原。

FileCookieJar.load(filename=None, ignore_discard=False, ignore_expires=False)

從檔案中載入 cookies。

舊的 cookies 會被保留,除非被新載入的 cookies 覆蓋。

引數與 save() 相同。

被命名的檔案必須是類別所能正確剖析的格式,否則會產生 LoadError。此外,OSError 可能會被引發,例如檔案不存在時。

在 3.3 版的變更: 以前會引發 IOError,現在它是 OSError 的別名。

FileCookieJar.revert(filename=None, ignore_discard=False, ignore_expires=False)

清除所有 cookies, 並從儲存的檔案重新載入 cookies。

revert() 可以產生與 load() 相同的例外。如果失敗,物件的狀態不會被改變。

FileCookieJar 實例擁有以下公開屬性:

FileCookieJar.filename

保存 cookie 的預設檔案的檔案名稱。 此屬性可以被指定。

FileCookieJar.delayload

若為 true,則從硬盤惰性地載入 cookies。 此屬性不應被指定。 這只是一個提示,因為這只會影響效能,不會影響行為 (除非磁碟上的 cookies 正在改變)。一個 CookieJar 物件可以忽略它。 沒有一個包含在標準函式庫中的 FileCookieJar 類別會惰性地載入 cookies。

FileCookieJar 子類別及與網頁瀏覽器的合作

以下 CookieJar 子類別提供用於讀取和寫入。

class http.cookiejar.MozillaCookieJar(filename=None, delayload=None, policy=None)

一個能夠以 Mozilla cookies.txt 檔案格式(該格式也被 curl 和 Lynx 以及 Netscape 瀏覽器所使用)從磁碟載入和儲存 cookie 的 FileCookieJar

備註

這會遺失關於 RFC 2965 cookie 的訊息,以及較新或非標準 cookie 屬性(例如 port)的訊息。

警告

如果 Cookie 遺失或損壞會造成不便,請在儲存之前先備份 Cookie(有些微妙的情況可能會導致檔案在載入/儲存往返過程中發生輕微變化)。

另外請注意,在 Mozilla 執行時儲存的 cookies 會被 Mozilla 刪除。

class http.cookiejar.LWPCookieJar(filename=None, delayload=None, policy=None)

一個 FileCookieJar 可以從 libwww-perl 函式庫的 Set-Cookie3 檔案格式載入 cookies 並儲存 cookies 到磁碟。如果你想要將 cookie 儲存在人類可讀的檔案中,這是很方便的。

在 3.8 版的變更: filename 參數支援傳入一個 path-like object

CookiePolicy objects

實作 CookiePolicy 介面的物件有以下方法:

CookiePolicy.set_ok(cookie, request)

回傳值表示的是否接受伺服器 cookie 的布林值。

cookie 是一個 Cookie 實例。 request 是一個實作了 CookieJar.extract_cookies() 文件所定義的介面的物件。

CookiePolicy.return_ok(cookie, request)

回傳布林值,表示 cookie 是否應回傳伺服器。

cookie 是一個 Cookie 實例。 request 是一個實作了 CookieJar.add_cookie_header() 文件所定義的介面的物件。

CookiePolicy.domain_return_ok(domain, request)

在給定 cookie 網域如果不應回傳 cookie,則回傳 False

此方法為一種最佳化。它消除了檢查每個具有特定網域的 cookie 的需要(這可能需要讀取許多檔案)。從 domain_return_ok()path_return_ok() 回傳 true 會把所有的工作留給 return_ok()

如果 domain_return_ok() 對 cookie 網域回傳 true,path_return_ok() 就會被用來呼叫 cookie 路徑。否則 path_return_ok()return_ok() 永遠不會被呼叫。如果 path_return_ok() 回傳 true,則會呼叫 return_ok() 附帶的 Cookie 物件本身以進行全面檢查。否則,return_ok() 將永遠不會被呼叫。

請注意,domain_return_ok() 是針對每個 cookie 網域來呼叫的,而不只是針對 request 網域。 例如,如果請求網域是 "www.example.com" ,這個函式可能會同時被 ".example.com""www.example.com" 呼叫。 同樣的道理也適用於 path_return_ok()

request 引數與 return_ok() 的說明文件相同。

CookiePolicy.path_return_ok(path, request)

給定 cookie 路徑如不應該回傳 cookie,則回傳 False

關於 domain_return_ok() 請見文件。

除了實作上述方法外, CookiePolicy 介面的實作也必須提供下列屬性,指出應該使用哪些通訊協定,以及如何使用。所有這些屬性都可以被指定。

CookiePolicy.netscape

實作 Netscape 協定。

CookiePolicy.rfc2965

實作 RFC 2965 協定。

CookiePolicy.hide_cookie2

不要在請求中加入 Cookie2 標頭(這個標頭的存在向伺服器表明我們能夠正確剖析 RFC 2965 cookie)。

DefaultCookiePolicy 為子類別定義 CookiePolicy 類別,並覆寫其中的一些或全部方法是最有用的。CookiePolicy 本身可以用做 '無策略',允許設定和接收任何和所有的 cookies (這不太可能有用)。

DefaultCookiePolicy objects

執行接受和回傳 cookie 的標準規則。

同時支援 RFC 2965 和 Netscape cookies。 RFC 2965 的處理預設為關閉。

提供你自己的策略的最簡單方法是覆寫此類別,並在你覆寫的實作中呼叫其方法,然後再加入你自己的額外檢查:

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

除了實作 CookiePolicy 介面所需的功能外,這個類別還允許你阻止或允許網域名稱設定和接收 cookies。 還有調整嚴格度的控制選項,可讓你稍微收緊相對寬鬆的 Netscape 通訊協定(代價是阻擋一些良性 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.

封鎖或允許清單中不以點開頭的網域必須與 cookie 網域相等才能匹配。 例如,"example.com" 會與封鎖清單項目 "example.com" 匹配,但 "www.example.com" 則不會。 以點開頭的網域也會與更特定的網域相匹配。例如,"www.example.com""www.coyote.example.com" 都匹配 ".example.com"(但 "example.com" 本身不匹配)。 IP 位址是例外,它們必須完全匹配。例如,如果 blocked_domains 包含 "192.168.1.2"".168.1.2",則 192.168.1.2 會被封鎖,但 193.168.1.2 則不會。

DefaultCookiePolicy 實作了下列附加方法:

DefaultCookiePolicy.blocked_domains()

回傳被阻止網域的序列(以元組形式)。

DefaultCookiePolicy.set_blocked_domains(blocked_domains)

設定阻止網域的順序。

DefaultCookiePolicy.is_blocked(domain)

如果 domain 在設定或接收 cookies 的阻止列表上,則回傳 True

DefaultCookiePolicy.allowed_domains()

Return 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)

如果 domain 不在設定或接收 cookies 的允許清單上,則回傳 True

DefaultCookiePolicy 實例有以下屬性,這些屬性都是由同名的建構函式引數初始化,而且都可以被指定。

DefaultCookiePolicy.rfc2109_as_netscape

If true, request that the CookieJar instance downgrade RFC 2109 cookies (that is, cookies received in a Set-Cookie 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

不允許網站設定具有國家代碼頂層域名的兩層域名,如 .co.uk.gov.uk.co.nz 等。 這遠遠不夠完美,也不能保證一定有效!

RFC 2965 通訊協定調整嚴格度的控制選項:

DefaultCookiePolicy.strict_rfc2965_unverifiable

遵循針對不可驗證事務(transaction)的 RFC 2965 規則(不可驗證事務通常是由重定向或請求發佈在其它網站的圖片導致的)。 如果該屬性為假值,則永遠不會基於可驗證性而阻止 cookie

Netscape 通訊協定調整嚴格度的控制選項:

DefaultCookiePolicy.strict_ns_unverifiable

即便是對 Netscape cookie 也要應用 RFC 2965 規則。

DefaultCookiePolicy.strict_ns_domain

指明針對 Netscape cookie 的網域匹配規則的嚴格程度。 可接受的值見下文。

DefaultCookiePolicy.strict_ns_set_initial_dollar

忽略 Set-Cookie: 標頭中名稱以 '$' 開頭的 cookies。

DefaultCookiePolicy.strict_ns_set_path

不允許設置路徑與請求 URL 路徑不匹配的 cookie。

strict_ns_domain 是一系列旗標。它的值由將旗標按位元或組成(例如,DomainStrictNoDots|DomainStrictNonDomain 表示兩個旗標都被設定)。

DefaultCookiePolicy.DomainStrictNoDots

When setting cookies, the 'host prefix' must not contain a dot (for example, www.foo.bar.com can't set a cookie for .bar.com, because 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 (for example, spam.example.com won't be returned cookies from example.com that had no domain cookie-attribute).

DefaultCookiePolicy.DomainRFC2965Match

設定 cookie 時,需要完整的 RFC 2965 網域匹配。

為了方便起見,以下屬性是上述旗標最有用的組合:

DefaultCookiePolicy.DomainLiberal

Equivalent to 0 (that is, all of the above Netscape domain strictness flags switched off).

DefaultCookiePolicy.DomainStrict

等價於 DomainStrictNoDots|DomainStrictNonDomain

範例

第一個範例展示了 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/")

本範例說明如何使用你的 Netscape、Mozilla 或 Lynx cookies 打開 URL (假設 Unix/Netscape 會慣用 cookies 檔案的位置):

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/")

下一個範例說明 DefaultCookiePolicy 的使用。開啟 RFC 2965 cookies,在設定和回傳 Netscape cookies 時對網域更嚴格,並阻止某些網域設定 cookies 或讓其回傳:

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/")