tornado.httputil — 操作 HTTP 標頭和 URL

由客戶端和伺服器共用的 HTTP 實用程式碼。

此模組還定義了 HTTPServerRequest 類別,該類別透過 tornado.web.RequestHandler.request 公開。

class tornado.httputil.HTTPHeaders(__arg: Mapping[str, List[str]])[原始碼]
class tornado.httputil.HTTPHeaders(__arg: Mapping[str, str])
class tornado.httputil.HTTPHeaders(*args: Tuple[str, str])
class tornado.httputil.HTTPHeaders(**kwargs: str)

一個字典,為所有鍵保留 Http-Header-Case

透過一對新方法 add()get_list() 支援每個鍵的多個值。常規字典介面每個鍵返回一個值,多個值以逗號連接。

>>> h = HTTPHeaders({"content-type": "text/html"})
>>> list(h.keys())
['Content-Type']
>>> h["Content-Type"]
'text/html'
>>> h.add("Set-Cookie", "A=B")
>>> h.add("Set-Cookie", "C=D")
>>> h["set-cookie"]
'A=B,C=D'
>>> h.get_list("set-cookie")
['A=B', 'C=D']
>>> for (k,v) in sorted(h.get_all()):
...    print('%s: %s' % (k,v))
...
Content-Type: text/html
Set-Cookie: A=B
Set-Cookie: C=D
add(name: str, value: str) None[原始碼]

為給定的鍵新增一個新值。

get_list(name: str) List[str][原始碼]

以列表形式返回給定標頭的所有值。

get_all() Iterable[Tuple[str, str]][原始碼]

返回所有 (名稱、值) 對的可迭代物件。

如果標頭有多個值,將返回具有相同名稱的多個對。

parse_line(line: str) None[原始碼]

使用單個標頭行更新字典。

>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html'
classmethod parse(headers: str) HTTPHeaders[原始碼]

從 HTTP 標頭文字返回字典。

>>> h = HTTPHeaders.parse("Content-Type: text/html\r\nContent-Length: 42\r\n")
>>> sorted(h.items())
[('Content-Length', '42'), ('Content-Type', 'text/html')]

在 5.1 版本中變更:在格式不正確的標頭上引發 HTTPInputError,而不是 KeyErrorValueError 的混合。

class tornado.httputil.HTTPServerRequest(method: Optional[str] = None, uri: Optional[str] = None, version: str = 'HTTP/1.0', headers: Optional[HTTPHeaders] = None, body: Optional[bytes] = None, host: Optional[str] = None, files: Optional[Dict[str, List[HTTPFile]]] = None, connection: Optional[HTTPConnection] = None, start_line: Optional[RequestStartLine] = None, server_connection: Optional[object] = None)[原始碼]

單一 HTTP 請求。

除非另有說明,否則所有屬性的類型皆為 str

method

HTTP 請求方法,例如 "GET" 或 "POST"

uri

請求的 URI。

path

uri 的路徑部分

query

uri 的查詢部分

version

請求中指定的 HTTP 版本,例如 "HTTP/1.1"

headers

用於請求標頭的類似字典的 HTTPHeaders 物件。行為類似不區分大小寫的字典,並具有用於重複標頭的附加方法。

body

如果存在,則請求主體為位元組字串。

remote_ip

客戶端的 IP 位址,以字串表示。如果設定 HTTPServer.xheaders,則會傳遞由負載平衡器在 X-Real-IpX-Forwarded-For 標頭中提供的實際 IP 位址。

變更於 3.1 版: 現在支援 X-Forwarded-For 的列表格式。

protocol

使用的協定,為 "http" 或 "https"。如果設定 HTTPServer.xheaders,則如果負載平衡器透過 X-Scheme 標頭回報,將傳遞負載平衡器使用的協定。

host

請求的主機名稱,通常取自 Host 標頭。

arguments

GET/POST 引數可在 arguments 屬性中使用,該屬性將引數名稱對應至值列表(以支援個別名稱的多個值)。名稱的類型為 str,而引數為位元組字串。請注意,這與 RequestHandler.get_argument 不同,後者會以 Unicode 字串形式傳回引數值。

query_arguments

arguments 格式相同,但僅包含從查詢字串擷取的引數。

3.2 版新增。

body_arguments

arguments 格式相同,但僅包含從請求主體擷取的引數。

3.2 版新增。

files

檔案上傳可在 files 屬性中使用,該屬性將檔案名稱對應至 HTTPFile 的清單。

connection

一個 HTTP 請求會附加到單一的 HTTP 連線上,此連線可透過 "connection" 屬性存取。由於在 HTTP/1.1 中連線通常會保持開啟,因此可以在單一連線上循序處理多個請求。

變更於 4.0 版本: tornado.httpserver.HTTPRequest 移動。

property cookies: Dict[str, Morsel]

一個 http.cookies.Morsel 物件的字典。

full_url() str[原始碼]

重建此請求的完整 URL。

request_time() float[原始碼]

傳回執行此請求所花費的時間量。

get_ssl_certificate(binary_form: bool = False) Union[None, Dict, bytes][原始碼]

傳回客戶端的 SSL 憑證(如果有的話)。

要使用客戶端憑證,必須設定 HTTPServer 的 ssl.SSLContext.verify_mode 欄位,例如:

ssl_ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
ssl_ctx.load_cert_chain("foo.crt", "foo.key")
ssl_ctx.load_verify_locations("cacerts.pem")
ssl_ctx.verify_mode = ssl.CERT_REQUIRED
server = HTTPServer(app, ssl_options=ssl_ctx)

預設情況下,傳回值是一個字典(如果沒有客戶端憑證,則為 None)。如果 binary_form 為 true,則會改為傳回憑證的 DER 編碼形式。請參閱標準函式庫中的 SSLSocket.getpeercert() 以了解更多詳細資訊。http://docs.python.org/library/ssl.html#sslsocket-objects

exception tornado.httputil.HTTPInputError[原始碼]

來自遠端來源的格式錯誤 HTTP 請求或回應的例外類別。

4.0 版本新增。

exception tornado.httputil.HTTPOutputError[原始碼]

HTTP 輸出錯誤的例外類別。

4.0 版本新增。

class tornado.httputil.HTTPServerConnectionDelegate[原始碼]

實作此介面以處理來自 HTTPServer 的請求。

4.0 版本新增。

start_request(server_conn: object, request_conn: HTTPConnection) HTTPMessageDelegate[原始碼]

當新的請求開始時,伺服器會呼叫此方法。

參數
  • server_conn – 是一個不透明的物件,代表持續存在的連線(例如,tcp 層級)。

  • request_conn – 是一個 HTTPConnection 物件,用於單一請求/回應交換。

此方法應傳回一個 HTTPMessageDelegate

on_close(server_conn: object) None[原始碼]

當連線已關閉時,會呼叫此方法。

參數

server_conn – 是先前已傳遞至 start_request 的伺服器連線。

class tornado.httputil.HTTPMessageDelegate[原始碼]

實作此介面以處理 HTTP 請求或回應。

4.0 版本新增。

headers_received(start_line: Union[RequestStartLine, ResponseStartLine], headers: HTTPHeaders) Optional[Awaitable[None]][原始碼]

當收到並解析 HTTP 標頭時呼叫。

參數

某些 HTTPConnection 方法只能在 headers_received 期間呼叫。

可以傳回一個 Future;如果這樣做,在完成之前不會讀取主體。

data_received(chunk: bytes) Optional[Awaitable[None]][原始碼]

當接收到資料區塊時呼叫。

可能會回傳一個 Future 以進行流量控制。

finish() None[原始碼]

在接收到最後一個資料區塊後呼叫。

on_connection_close() None[原始碼]

如果連線在未完成請求的情況下關閉,則會呼叫此方法。

如果呼叫了 headers_received,則會呼叫 finishon_connection_close,但不會同時呼叫兩者。

class tornado.httputil.HTTPConnection[原始碼]

應用程式使用此介面來寫入它們的回應。

4.0 版本新增。

write_headers(start_line: Union[RequestStartLine, ResponseStartLine], headers: HTTPHeaders, chunk: Optional[bytes] = None) Future[None][原始碼]

寫入一個 HTTP 標頭區塊。

參數
  • start_line – 一個 RequestStartLineResponseStartLine

  • headers – 一個 HTTPHeaders 實例。

  • chunk – 第一個(可選)資料區塊。這是一種最佳化,以便可以在與標頭相同的呼叫中寫入小型回應。

start_lineversion 欄位會被忽略。

回傳一個用於流程控制的 future。

變更於 6.0 版: 已移除 callback 引數。

write(chunk: bytes) Future[None][原始碼]

寫入一個主體資料區塊。

回傳一個用於流程控制的 future。

變更於 6.0 版: 已移除 callback 引數。

finish() None[原始碼]

表示已寫入最後的主體資料。

tornado.httputil.url_concat(url: str, args: Union[None, Dict[str, str], List[Tuple[str, str]], Tuple[Tuple[str, str], ...]]) str[原始碼]

連接網址和引數,無論網址是否有現有的查詢引數。

args 可以是字典或鍵值對列表(後者允許同一鍵有多個值)。

>>> url_concat("http://example.com/foo", dict(c="d"))
'http://example.com/foo?c=d'
>>> url_concat("http://example.com/foo?a=b", dict(c="d"))
'http://example.com/foo?a=b&c=d'
>>> url_concat("http://example.com/foo?a=b", [("c", "d"), ("c", "d2")])
'http://example.com/foo?a=b&c=d&c=d2'
class tornado.httputil.HTTPFile[原始碼]

表示透過表單上傳的檔案。

為了向後相容,它的實例屬性也可以作為字典鍵存取。

  • filename

  • body

  • content_type

tornado.httputil.parse_body_arguments(content_type: str, body: bytes, arguments: Dict[str, List[bytes]], files: Dict[str, List[HTTPFile]], headers: Optional[HTTPHeaders] = None) None[原始碼]

解析表單請求的主體。

支援 application/x-www-form-urlencodedmultipart/form-datacontent_type 參數應為字串,而 body 應為位元組字串。 argumentsfiles 參數是字典,將使用解析後的內容進行更新。

tornado.httputil.parse_multipart_form_data(boundary: bytes, data: bytes, arguments: Dict[str, List[bytes]], files: Dict[str, List[HTTPFile]]) None[原始碼]

解析 multipart/form-data 主體。

boundarydata 參數都是位元組字串。 arguments 和 files 參數中給定的字典將使用主體的內容進行更新。

變更於版本 5.1: 現在可辨識 RFC 2231/5987 中的非 ASCII 檔名(filename*=)格式。

tornado.httputil.format_timestamp(ts: Union[int, float, tuple, struct_time, datetime]) str[原始碼]

以 HTTP 使用的格式格式化時間戳記。

引數可以是 time.time 回傳的數值時間戳記,time.gmtime 回傳的時間元組,或是 datetime.datetime 物件。 假定簡單的 datetime.datetime 物件表示 UTC;在格式化之前,會將感知型物件轉換為 UTC。

>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'
class tornado.httputil.RequestStartLine(method, path, version)

RequestStartLine(method, path, version)

建立 RequestStartLine(method, path, version) 的新實例

method

欄位編號 0 的別名

path

欄位編號 1 的別名

version

欄位編號 2 的別名

tornado.httputil.parse_request_start_line(line: str) RequestStartLine[原始碼]

為 HTTP 1.x 請求行傳回 (method, path, version) 元組。

回應為 collections.namedtuple

>>> parse_request_start_line("GET /foo HTTP/1.1")
RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')
class tornado.httputil.ResponseStartLine(version, code, reason)

ResponseStartLine(version, code, reason)

建立 ResponseStartLine(version, code, reason) 的新實例

code

欄位編號 1 的別名

reason

欄位編號 2 的別名

version

欄位編號 0 的別名

tornado.httputil.parse_response_start_line(line: str) ResponseStartLine[原始碼]

針對 HTTP 1.x 的回應行,回傳 (版本, 代碼, 原因) 的元組。

回應為 collections.namedtuple

>>> parse_response_start_line("HTTP/1.1 200 OK")
ResponseStartLine(version='HTTP/1.1', code=200, reason='OK')
tornado.httputil.encode_username_password(username: Union[str, bytes], password: Union[str, bytes]) bytes[原始碼]

將使用者名稱/密碼對編碼成 HTTP 驗證所使用的格式。

回傳值為 username:password 形式的位元組字串。

在 5.1 版本中新增。

tornado.httputil.split_host_and_port(netloc: str) Tuple[str, Optional[int]][原始碼]

netloc 回傳 (host, port) 元組。

若不存在,則回傳的 port 將為 None

在 4.1 版本中新增。

tornado.httputil.qs_to_qsl(qs: Dict[str, List]) Iterable[Tuple[str, AnyStr]][原始碼]

產生器將 parse_qs 的結果轉換回名稱-值對。

在 5.0 版本中新增。

Cookie HTTP 標頭解析為名稱/值對的字典。

此函數嘗試模擬瀏覽器 cookie 解析行為;特別是不遵循任何與 cookie 相關的 RFC(因為瀏覽器也不遵循)。

所使用的演算法與 Django 1.9.10 版使用的演算法相同。

在 4.4.2 版本中新增。