urllib.request --- 用來開啟 URLs 的可擴充函式庫¶
urllib.request module(模組)定義了一些函式與 class(類別)用以開啟 URLs(大部分是 HTTP),並處理各式複雜情況如:basic 驗證與 digest 驗證、重新導向、cookies。
也參考
有關於更高階的 HTTP 用戶端介面,推薦使用 Requests 套件。
警告
On macOS it is unsafe to use this module in programs using
os.fork() because the getproxies() implementation for
macOS uses a higher-level system API. Set the environment variable
no_proxy to * to avoid this problem
(e.g. os.environ["no_proxy"] = "*").
可用性: not WASI.
此模組在 WebAssembly 平台上不起作用或無法使用。更多資訊請參閱 WebAssembly 平台。
urllib.request module 定義下列函式:
- urllib.request.urlopen(url, data=None, [timeout, ]*, context=None)¶
打開 url,其值可以是一個包含有效且適當編碼 URL 的字串或是一個
Request物件。data 必須是一個包含傳送給伺服器額外資料的物件,若不需要傳送額外資料則指定為
None。更多細節請見Request。urllib.request module 使用 HTTP/1.1 並包含
Connection:closeheader(標頭)在其 HTTP 請求中。透過選擇性參數 timeout 來指定 blocking operations(阻塞性操作,如:嘗試連接)的 timeout(超時時間),以秒為單位。若沒有指定值,則會使用全域預設超時時間設定。實際上,此參數僅作用於 HTTP、HTTPS 以及 FTP 的連接。
若 context 有被指定時,它必須是一個
ssl.SSLContext的實例並描述著各種 SSL 選項。更多細節請見HTTPSConnection。這個函式總是回傳一個可作為 context manager 使用的物件,並有著特性 (property) url、headers 與 status。欲知更多這些特性細節請參見
urllib.response.addinfourl。對於 HTTP 與 HTTPS 的 URLs,這個函式回傳一個稍有不同的
http.client.HTTPResponse物件。除了上述提到的三個方法外,另有 msg 屬性並有著與reason相同的資訊 --- 由伺服器回傳的原因敘述 (reason phrase),而不是在HTTPResponse文件中提到的回應 headers。對於 FTP、檔案及資料的 URLs,這個函式會回傳一個
urllib.response.addinfourl物件。當遇到協定上的錯誤時會引發
URLError。請注意若沒有 handler 處理請求時,
None值將會被回傳。(即使有預設的全域類別OpenerDirector使用UnknownHandler來確保這種情況不會發生)另外,若有偵測到代理服務的設定(例如當
*_proxy環境變數像是::envvar:!http_proxy` 有被設置時),ProxyHandler會被預設使用以確保請求有透過代理服務來處理。Python 2.6 或更早版本的遺留函式
urllib.urlopen已經不再被維護;新函式urllib.request.urlopen()對應到舊函式urllib2.urlopen。有關代理服務的處理,以往是透過傳遞 dictionary(字典)參數給urllib.urlopen來取得的,現在則可以透過ProxyHandler物件來取得。預設的 opener 會觸發一個 auditing event
urllib.Request與其從請求物件中所獲得的引數fullurl、data、headers、method。在 3.2 版的變更: 新增 cafile 與 capath。
HTTPS 虛擬主機 (virtual hosts) 現已支援,只要
ssl.HAS_SNI的值為 true。data 可以是一個可疊代物件。
在 3.3 版的變更: cadefault 被新增。
在 3.4.3 版的變更: context 被新增。
在 3.10 版的變更: 當 context 沒有被指定時,HTTPS 連線現在會傳送一個帶有協定指示器
http/1.1的 ALPN 擴充 (extension)。自訂的 context 應該利用set_alpn_protocols()來自行設定 ALPN 協定。在 3.13 版的變更: Remove cafile, capath and cadefault parameters: use the context parameter instead.
- urllib.request.install_opener(opener)¶
安裝一個
OpenerDirector實例作為預設的全域 opener。僅在當你想要讓 urlopen 使用該 opener 時安裝一個 opener,否則的話應直接呼叫OpenerDirector.open()而非urlopen()。程式碼不會檢查 class 是否真的為OpenerDirector,而是任何具有正確介面的 class 都能適用。
- urllib.request.build_opener([handler, ...])¶
回傳一個
OpenerDirector實例,以給定的順序把 handlers 串接起來。handlers 可以是BaseHandler的實例,亦或是BaseHandler的 subclasses(這個情況下必須有不帶參數的建構函式能夠被呼叫)。以下 classes 的實例順位會在 handlers 之前,除非 handlers 已經包含它們,是它們的實例,或是它們的 subclasses:ProxyHandler(如果代理服務設定被偵測到)、UnknownHandler、HTTPHandler、HTTPDefaultErrorHandler、HTTPRedirectHandler、FTPHandler、FileHandler、HTTPErrorProcessor。如果 Python 安裝時已帶有 SSL 支援(如果
sslmodule 能夠被 import),則HTTPSHandler也在上述 class 之中。一個
BaseHandler的 subclass 可能透過改變其handler_order屬性來調整它在 handlers list 中的位置。
- urllib.request.pathname2url(path, *, add_scheme=False)¶
Convert the given local path to a
file:URL. This function usesquote()function to encode the path.If add_scheme is false (the default), the return value omits the
file:scheme prefix. Set add_scheme to true to return a complete URL.This example shows the function being used on Windows:
>>> from urllib.request import pathname2url >>> path = 'C:\\Program Files' >>> pathname2url(path, add_scheme=True) 'file:///C:/Program%20Files'
在 3.14 版的變更: Windows drive letters are no longer converted to uppercase, and
:characters not following a drive letter no longer cause anOSErrorexception to be raised on Windows.在 3.14 版的變更: Paths beginning with a slash are converted to URLs with authority sections. For example, the path
/etc/hostsis converted to the URL///etc/hosts.在 3.14 版的變更: 新增 add_scheme 參數。
- urllib.request.url2pathname(url, *, require_scheme=False, resolve_host=False)¶
Convert the given
file:URL to a local path. This function usesunquote()to decode the URL.If require_scheme is false (the default), the given value should omit a
file:scheme prefix. If require_scheme is set to true, the given value should include the prefix; aURLErroris raised if it doesn't.The URL authority is discarded if it is empty,
localhost, or the local hostname. Otherwise, if resolve_host is set to true, the authority is resolved usingsocket.gethostbyname()and discarded if it matches a local IP address (as per RFC 8089 §3). If the authority is still unhandled, then on Windows a UNC path is returned, and on other platforms aURLErroris raised.This example shows the function being used on Windows:
>>> from urllib.request import url2pathname >>> url = 'file:///C:/Program%20Files' >>> url2pathname(url, require_scheme=True) 'C:\\Program Files'
在 3.14 版的變更: Windows drive letters are no longer converted to uppercase, and
:characters not following a drive letter no longer cause anOSErrorexception to be raised on Windows.在 3.14 版的變更: The URL authority is discarded if it matches the local hostname. Otherwise, if the authority isn't empty or
localhost, then on Windows a UNC path is returned (as before), and on other platforms aURLErroris raised.在 3.14 版的變更: The URL query and fragment components are discarded if present.
在 3.14 版的變更: The require_scheme and resolve_host parameters were added.
- urllib.request.getproxies()¶
這個輔助函式 (helper function) 回傳一個代理伺服器 URL mappings(對映)的 dictionary。在所有的作業系統中,它首先掃描環境中有著
<scheme>_proxy名稱的變數(忽略大小寫的),如果找不到的話就會在 macOS 中的系統設定 (System Configuration) 或是 Windows 系統中的 Windows Systems Registry 尋找代理服務設定。如果大小寫的環境變數同時存在且值有不同,小寫的環境變數會被選用。備註
如果環境變數
REQUEST_METHOD有被設置(通常這代表著你的 script 是運行在一個共用閘道介面 (CGI) 環境中),那麼環境變數HTTP_PROXY(大寫的_PROXY)將被忽略。這是因為變數可以透過使用 "Proxy:" HTTP header 被注入。如果需要在共用閘道介面環境中使用 HTTP 代理服務,可以明確使用ProxyHandler,亦或是確認變數名稱是小寫的(或至少_proxy後綴是小寫的)。
提供了以下的 classes:
- class urllib.request.Request(url, data=None, headers={}, origin_req_host=None, unverifiable=False, method=None)¶
這個 class 是一個 URL 請求的抽象 class。
url 是一個包含有效且適當編碼的 URL 字串。
data 必須是一個包含要送到伺服器的附加資料的物件,若不需帶附加資料則其值應為
None。目前 HTTP 請求是唯一有使用 data 參數的,其支援的物件型別包含位元組、類檔案物件 (file-like objects)、以及可疊代的類位元組串物件 (bytes-like objects)。如果沒有提供Content-Length及Transfer-Encodingheaders 欄位,HTTPHandler將會根據 data 的型別設置這些 header。Content-Length會被用來傳送位元組串物件,而 RFC 7230 章節 3.3.1 所定義的Transfer-Encoding: chunked則會被用來傳送檔案或是其它可疊代物件 (iterables)。對於一個 HTTP POST 請求方法,data 應為一個標準 application/x-www-form-urlencoded 格式的 buffer。
urllib.parse.urlencode()方法接受一個 mapping 或是 sequence(序列)的 2-tuples,並回傳一個對應格式的 ASCII 字串。在被作為 data 參數前它應該被編碼成位元組串。headers 必須是一個 dictionary,並會被視為如同每對 key 和 value 作為引數來呼叫
add_header()。經常用於「偽裝」User-Agentheader 的值,這個 header 是用來讓一個瀏覽器向伺服器表明自己的身分 --- 有些 HTTP 伺服器僅允許來自普通瀏覽器的請求,而不接受來自程式腳本的請求。例如,Mozilla Firefox 會將 header 的值設為"Mozilla/5.0 (X11; U; Linux i686) Gecko/20071127 Firefox/2.0.0.11",而urllib的值則是"Python-urllib/2.6"(在 Python 2.6 上)。所有 header 的鍵都會以 camel case(駝峰式大小寫)來傳送。當有給定 data 引數時,一個適當的
Content-Typeheader 應該被設置。如果這個 header 沒有被提供且 data 也不為None時,預設值Content-Type: application/x-www-form-urlencoded會被新增至請求中。接下來的兩個引數的介紹提供給那些有興趣正確處理第三方 HTTP cookies 的使用者:
origin_req_host 應為原始傳輸互動的請求主機 (request-host),如同在 RFC 2965 中的定義。預設值為
http.cookiejar.request_host(self)。這是使用者發起的原始請求的主機名稱或是 IP 位址。例如當請求是要求一個 HTML 文件中的一個影像,則這個屬性應為請求包含影像頁面的請求主機。unverifiable 應該標示一個請求是否是無法驗證的,如同在 RFC 2965 中的定義。其預設值為
False。一個無法驗證的請求是指使用者沒有機會去批准請求的 URL,例如一個對於 HTML 文件中的影像所做的請求,而使用者沒有機會去批准是否能自動擷取影像,則這個值應該為 true。method 應為一個標示 HTTP 請求方法的字串(例如:
'HEAD')。如果有提供值,則會被存在method屬性中且被get_method()所使用。當 data 是None時,其預設值為'GET',否則預設值為'POST'。Subclasses 可以透過設置其method屬性來設定不一樣的預設請求方法。備註
如果資料物件無法重複提供其內容(例如一個檔案或是只能產生一次內容的可疊代物件)且請求因為 HTTP 重導向 (redirects) 或是 HTTP 驗證 (authentication) 而被重新嘗試傳送,則該請求不會正常運作。data 會接在 headers 之後被送至 HTTP 伺服器。此函式庫沒有支援 100-continue expectation。
在 3.3 版的變更: 新增
Request.method引數到 Request class。在 3.4 版的變更: 能夠在 class 中設置預設的
Request.method。在 3.6 版的變更: 如果
Content-Length尚未被提供且 data 既不是None也不是一個位元組串物件,則不會觸發錯誤,並 fall back(後備)使用分塊傳輸編碼 (chunked transfer encoding)。
- class urllib.request.OpenerDirector¶
The
OpenerDirectorclass opens URLs viaBaseHandlers chained together. It manages the chaining of handlers, and recovery from errors.
- class urllib.request.BaseHandler¶
This is the base class for all registered handlers --- and handles only the simple mechanics of registration.
- class urllib.request.HTTPDefaultErrorHandler¶
A class which defines a default handler for HTTP error responses; all responses are turned into
HTTPErrorexceptions.
- class urllib.request.HTTPRedirectHandler¶
用於處理重新導向的類別。
- class urllib.request.HTTPCookieProcessor(cookiejar=None)¶
用於處理 HTTP Cookie 的類別。
- class urllib.request.ProxyHandler(proxies=None)¶
Cause requests to go through a proxy. If proxies is given, it must be a dictionary mapping protocol names to URLs of proxies. The default is to read the list of proxies from the environment variables
<protocol>_proxy. If no proxy environment variables are set, then in a Windows environment proxy settings are obtained from the registry's Internet Settings section, and in a macOS environment proxy information is retrieved from the System Configuration Framework.To disable autodetected proxy pass an empty dictionary.
The
no_proxyenvironment variable can be used to specify hosts which shouldn't be reached via proxy; if set, it should be a comma-separated list of hostname suffixes, optionally with:portappended, for examplecern.ch,ncsa.uiuc.edu,some.host:8080.備註
HTTP_PROXYwill be ignored if a variableREQUEST_METHODis set; see the documentation ongetproxies().
- class urllib.request.HTTPPasswordMgr¶
Keep a database of
(realm, uri) -> (user, password)mappings.
- class urllib.request.HTTPPasswordMgrWithDefaultRealm¶
Keep a database of
(realm, uri) -> (user, password)mappings. A realm ofNoneis considered a catch-all realm, which is searched if no other realm fits.
- class urllib.request.HTTPPasswordMgrWithPriorAuth¶
A variant of
HTTPPasswordMgrWithDefaultRealmthat also has a database ofuri -> is_authenticatedmappings. Can be used by a BasicAuth handler to determine when to send authentication credentials immediately instead of waiting for a401response first.在 3.5 版被加入.
- class urllib.request.AbstractBasicAuthHandler(password_mgr=None)¶
This is a mixin class that helps with HTTP authentication, both to the remote host and to a proxy. password_mgr, if given, should be something that is compatible with
HTTPPasswordMgr; refer to section HTTPPasswordMgr 物件 for information on the interface that must be supported. If passwd_mgr also providesis_authenticatedandupdate_authenticatedmethods (see HTTPPasswordMgrWithPriorAuth 物件), then the handler will use theis_authenticatedresult for a given URI to determine whether or not to send authentication credentials with the request. Ifis_authenticatedreturnsTruefor the URI, credentials are sent. Ifis_authenticatedisFalse, credentials are not sent, and then if a401response is received the request is re-sent with the authentication credentials. If authentication succeeds,update_authenticatedis called to setis_authenticatedTruefor the URI, so that subsequent requests to the URI or any of its super-URIs will automatically include the authentication credentials.在 3.5 版被加入: 新增
is_authenticated的支援。
- class urllib.request.HTTPBasicAuthHandler(password_mgr=None)¶
Handle authentication with the remote host. password_mgr, if given, should be something that is compatible with
HTTPPasswordMgr; refer to section HTTPPasswordMgr 物件 for information on the interface that must be supported. HTTPBasicAuthHandler will raise aValueErrorwhen presented with a wrong Authentication scheme.
- class urllib.request.ProxyBasicAuthHandler(password_mgr=None)¶
Handle authentication with the proxy. password_mgr, if given, should be something that is compatible with
HTTPPasswordMgr; refer to section HTTPPasswordMgr 物件 for information on the interface that must be supported.
- class urllib.request.AbstractDigestAuthHandler(password_mgr=None)¶
This is a mixin class that helps with HTTP authentication, both to the remote host and to a proxy. password_mgr, if given, should be something that is compatible with
HTTPPasswordMgr; refer to section HTTPPasswordMgr 物件 for information on the interface that must be supported.在 3.14 版的變更: Added support for HTTP digest authentication algorithm
SHA-256.
- class urllib.request.HTTPDigestAuthHandler(password_mgr=None)¶
Handle authentication with the remote host. password_mgr, if given, should be something that is compatible with
HTTPPasswordMgr; refer to section HTTPPasswordMgr 物件 for information on the interface that must be supported. When both Digest Authentication Handler and Basic Authentication Handler are both added, Digest Authentication is always tried first. If the Digest Authentication returns a 40x response again, it is sent to Basic Authentication handler to Handle. This Handler method will raise aValueErrorwhen presented with an authentication scheme other than Digest or Basic.在 3.3 版的變更: 針對不支援的驗證方案 (Authentication Scheme) 引發
ValueError。
- class urllib.request.ProxyDigestAuthHandler(password_mgr=None)¶
Handle authentication with the proxy. password_mgr, if given, should be something that is compatible with
HTTPPasswordMgr; refer to section HTTPPasswordMgr 物件 for information on the interface that must be supported.
- class urllib.request.HTTPHandler¶
用於處理開啟 HTTP URL 的類別。
- class urllib.request.HTTPSHandler(debuglevel=0, context=None, check_hostname=None)¶
A class to handle opening of HTTPS URLs. context and check_hostname have the same meaning as in
http.client.HTTPSConnection.在 3.2 版的變更: 新增 context 與 check_hostname。
- class urllib.request.FileHandler¶
Open local files.
- class urllib.request.DataHandler¶
Open data URLs.
在 3.4 版被加入.
- class urllib.request.FTPHandler¶
打開 FTP URLs。
- class urllib.request.CacheFTPHandler¶
Open FTP URLs, keeping a cache of open FTP connections to minimize delays.
- class urllib.request.UnknownHandler¶
A catch-all class to handle unknown URLs.
- class urllib.request.HTTPErrorProcessor¶
Process HTTP error responses.
Request 物件¶
The following methods describe Request's public interface,
and so all may be overridden in subclasses. It also defines several
public attributes that can be used by clients to inspect the parsed
request.
- Request.full_url¶
The original URL passed to the constructor.
在 3.4 版的變更.
Request.full_url is a property with setter, getter and a deleter. Getting
full_urlreturns the original request URL with the fragment, if it was present.
- Request.type¶
The URI scheme.
- Request.host¶
The URI authority, typically a host, but may also contain a port separated by a colon.
- Request.origin_req_host¶
The original host for the request, without port.
- Request.selector¶
The URI path. If the
Requestuses a proxy, then selector will be the full URL that is passed to the proxy.
- Request.data¶
The entity body for the request, or
Noneif not specified.在 3.4 版的變更: Changing value of
Request.datanow deletes "Content-Length" header if it was previously set or calculated.
- Request.unverifiable¶
boolean, indicates whether the request is unverifiable as defined by RFC 2965.
- Request.method¶
The HTTP request method to use. By default its value is
None, which means thatget_method()will do its normal computation of the method to be used. Its value can be set (thus overriding the default computation inget_method()) either by providing a default value by setting it at the class level in aRequestsubclass, or by passing a value in to theRequestconstructor via the method argument.在 3.3 版被加入.
在 3.4 版的變更: A default value can now be set in subclasses; previously it could only be set via the constructor argument.
- Request.get_method()¶
Return a string indicating the HTTP request method. If
Request.methodis notNone, return its value, otherwise return'GET'ifRequest.dataisNone, or'POST'if it's not. This is only meaningful for HTTP requests.在 3.3 版的變更: get_method now looks at the value of
Request.method.
- Request.add_header(key, val)¶
Add another header to the request. Headers are currently ignored by all handlers except HTTP handlers, where they are added to the list of headers sent to the server. Note that there cannot be more than one header with the same name, and later calls will overwrite previous calls in case the key collides. Currently, this is no loss of HTTP functionality, since all headers which have meaning when used more than once have a (header-specific) way of gaining the same functionality using only one header. Note that headers added using this method are also added to redirected requests.
- Request.add_unredirected_header(key, header)¶
Add a header that will not be added to a redirected request.
- Request.has_header(header)¶
Return whether the instance has the named header (checks both regular and unredirected).
- Request.remove_header(header)¶
Remove named header from the request instance (both from regular and unredirected headers).
在 3.4 版被加入.
- Request.get_full_url()¶
Return the URL given in the constructor.
在 3.4 版的變更.
- Request.set_proxy(host, type)¶
Prepare the request by connecting to a proxy server. The host and type will replace those of the instance, and the instance's selector will be the original URL given in the constructor.
- Request.get_header(header_name, default=None)¶
Return the value of the given header. If the header is not present, return the default value.
- Request.header_items()¶
Return a list of tuples (header_name, header_value) of the Request headers.
在 3.4 版的變更: The request methods add_data, has_data, get_data, get_type, get_host, get_selector, get_origin_req_host and is_unverifiable that were deprecated since 3.3 have been removed.
OpenerDirector 物件¶
OpenerDirector 物件有以下的方法:
- OpenerDirector.add_handler(handler)¶
handler should be an instance of
BaseHandler. The following methods are searched, and added to the possible chains (note that HTTP errors are a special case). Note that, in the following, protocol should be replaced with the actual protocol to handle, for examplehttp_response()would be the HTTP protocol response handler. Also type should be replaced with the actual HTTP code, for examplehttp_error_404()would handle HTTP 404 errors.<protocol>_open()--- signal that the handler knows how to open protocol URLs.更多資訊請見
BaseHandler.<protocol>_open()。http_error_<type>()--- signal that the handler knows how to handle HTTP errors with HTTP error code type.更多資訊請見
BaseHandler.http_error_<nnn>()。<protocol>_error()--- signal that the handler knows how to handle errors from (non-http) protocol.<protocol>_request()--- signal that the handler knows how to pre-process protocol requests.更多資訊請見
BaseHandler.<protocol>_request()。<protocol>_response()--- signal that the handler knows how to post-process protocol responses.
- OpenerDirector.open(url, data=None[, timeout])¶
Open the given url (which can be a request object or a string), optionally passing the given data. Arguments, return values and exceptions raised are the same as those of
urlopen()(which simply calls theopen()method on the currently installed globalOpenerDirector). The optional timeout parameter specifies a timeout in seconds for blocking operations like the connection attempt (if not specified, the global default timeout setting will be used). The timeout feature actually works only for HTTP, HTTPS and FTP connections.
- OpenerDirector.error(proto, *args)¶
Handle an error of the given protocol. This will call the registered error handlers for the given protocol with the given arguments (which are protocol specific). The HTTP protocol is a special case which uses the HTTP response code to determine the specific error handler; refer to the
http_error_<type>()methods of the handler classes.Return values and exceptions raised are the same as those of
urlopen().
OpenerDirector objects open URLs in three stages:
The order in which these methods are called within each stage is determined by sorting the handler instances.
Every handler with a method named like
<protocol>_request()has that method called to pre-process the request.Handlers with a method named like
<protocol>_open()are called to handle the request. This stage ends when a handler either returns a non-Nonevalue (ie. a response), or raises an exception (usuallyURLError). Exceptions are allowed to propagate.In fact, the above algorithm is first tried for methods named
default_open(). If all such methods returnNone, the algorithm is repeated for methods named like<protocol>_open(). If all such methods returnNone, the algorithm is repeated for methods namedunknown_open().Note that the implementation of these methods may involve calls of the parent
OpenerDirectorinstance'sopen()anderror()methods.Every handler with a method named like
<protocol>_response()has that method called to post-process the response.
BaseHandler 物件¶
BaseHandler objects provide a couple of methods that are directly
useful, and others that are meant to be used by derived classes. These are
intended for direct use:
- BaseHandler.add_parent(director)¶
Add a director as parent.
- BaseHandler.close()¶
Remove any parents.
The following attribute and methods should only be used by classes derived from
BaseHandler.
備註
The convention has been adopted that subclasses defining
<protocol>_request() or <protocol>_response() methods are named
*Processor; all others are named *Handler.
- BaseHandler.parent¶
A valid
OpenerDirector, which can be used to open using a different protocol, or handle errors.
- BaseHandler.default_open(req)¶
This method is not defined in
BaseHandler, but subclasses should define it if they want to catch all URLs.This method, if implemented, will be called by the parent
OpenerDirector. It should return a file-like object as described in the return value of theopen()method ofOpenerDirector, orNone. It should raiseURLError, unless a truly exceptional thing happens (for example,MemoryErrorshould not be mapped toURLError).This method will be called before any protocol-specific open method.
- BaseHandler.<protocol>_open(req)
This method is not defined in
BaseHandler, but subclasses should define it if they want to handle URLs with the given protocol.This method, if defined, will be called by the parent
OpenerDirector. Return values should be the same as fordefault_open().
- BaseHandler.unknown_open(req)¶
This method is not defined in
BaseHandler, but subclasses should define it if they want to catch all URLs with no specific registered handler to open it.This method, if implemented, will be called by the
parentOpenerDirector. Return values should be the same as fordefault_open().
- BaseHandler.http_error_default(req, fp, code, msg, hdrs)¶
This method is not defined in
BaseHandler, but subclasses should override it if they intend to provide a catch-all for otherwise unhandled HTTP errors. It will be called automatically by theOpenerDirectorgetting the error, and should not normally be called in other circumstances.OpenerDirector會以五個位置引數呼叫此方法:一個
Request物件一個類檔案物件,包含 HTTP 錯誤主體,
HTTP 錯誤的三位數代號字串,
HTTP 錯誤代號的使用者可見解釋字串,以及
HTTP 錯誤的標頭,為一個對映物件。
Return values and exceptions raised should be the same as those of
urlopen().
- BaseHandler.http_error_<nnn>(req, fp, code, msg, hdrs)
nnn should be a three-digit HTTP error code. This method is also not defined in
BaseHandler, but will be called, if it exists, on an instance of a subclass, when an HTTP error with code nnn occurs.Subclasses should override this method to handle specific HTTP errors.
Arguments, return values and exceptions raised should be the same as for
http_error_default().
- BaseHandler.<protocol>_request(req)
This method is not defined in
BaseHandler, but subclasses should define it if they want to pre-process requests of the given protocol.This method, if defined, will be called by the parent
OpenerDirector. req will be aRequestobject. The return value should be aRequestobject.
- BaseHandler.<protocol>_response(req, response)
This method is not defined in
BaseHandler, but subclasses should define it if they want to post-process responses of the given protocol.This method, if defined, will be called by the parent
OpenerDirector. req will be aRequestobject. response will be an object implementing the same interface as the return value ofurlopen(). The return value should implement the same interface as the return value ofurlopen().
HTTPRedirectHandler 物件¶
備註
Some HTTP redirections require action from this module's client code. If this
is the case, HTTPError is raised. See RFC 2616 for
details of the precise meanings of the various redirection codes.
An HTTPError exception raised as a security consideration if the
HTTPRedirectHandler is presented with a redirected URL which is not an HTTP,
HTTPS or FTP URL.
- HTTPRedirectHandler.redirect_request(req, fp, code, msg, hdrs, newurl)¶
Return a
RequestorNonein response to a redirect. This is called by the default implementations of thehttp_error_30*()methods when a redirection is received from the server. If a redirection should take place, return a newRequestto allowhttp_error_30*()to perform the redirect to newurl. Otherwise, raiseHTTPErrorif no other handler should try to handle this URL, or returnNoneif you can't but another handler might.備註
The default implementation of this method does not strictly follow RFC 2616, which says that 301 and 302 responses to
POSTrequests must not be automatically redirected without confirmation by the user. In reality, browsers do allow automatic redirection of these responses, changing the POST to aGET, and the default implementation reproduces this behavior.
- HTTPRedirectHandler.http_error_301(req, fp, code, msg, hdrs)¶
Redirect to the
Location:orURI:URL. This method is called by the parentOpenerDirectorwhen getting an HTTP 'moved permanently' response.
- HTTPRedirectHandler.http_error_302(req, fp, code, msg, hdrs)¶
The same as
http_error_301(), but called for the 'found' response.
- HTTPRedirectHandler.http_error_303(req, fp, code, msg, hdrs)¶
The same as
http_error_301(), but called for the 'see other' response.
- HTTPRedirectHandler.http_error_307(req, fp, code, msg, hdrs)¶
The same as
http_error_301(), but called for the 'temporary redirect' response. It does not allow changing the request method fromPOSTtoGET.
- HTTPRedirectHandler.http_error_308(req,