Tornado 操作HTTP表頭和URL

2022-03-09 18:07 更新

客戶端和服務(wù)器共享的 HTTP 實(shí)用程序代碼。

該模塊還定義了通過 ?tornado.web.RequestHandler.request? 公開的 ?HTTPServerRequest? 類。

class tornado.httputil.HTTPHeaders(*args, **kwargs)

為?Http-Header-Case?保留所有鑰匙的字典。
通過一對(duì)新方法?add()?和?get_list()?,每個(gè)鍵支持多個(gè)值。常規(guī)字典接口為每個(gè)鍵返回一個(gè)值,多個(gè)值之間用逗號(hào)連接。

>>> 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]]

返回所有 (name, value) 對(duì)的可迭代對(duì)象。

如果一個(gè)表頭有多個(gè)值,將返回多個(gè)具有相同名稱的對(duì)。

parse_line(line: str) → None

使用單個(gè)標(biāo)題行更新字典。

>>> h = HTTPHeaders()
>>> h.parse_line("Content-Type: text/html")
>>> h.get('content-type')
'text/html'

classmethod parse(headers: str) → tornado.httputil.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')]

class tornado.httputil.HTTPServerRequest(method: Optional[str] = None, uri: Optional[str] = None, version: str = 'HTTP/1.0', headers: Optional[tornado.httputil.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)

單個(gè) HTTP 請(qǐng)求。

除非另有說明,否則所有屬性都是 str 類型。

  • ?method?:HTTP 請(qǐng)求方法,例如 “GET”或“POST”
  • ?uri?:請(qǐng)求的 uri。
  • ?path?:uri 的路徑部分
  • ?query?:uri的查詢部分
  • ?version?:請(qǐng)求中指定的 HTTP 版本,例如 “HTTP/1.1”
  • ?headers?:HTTPHeaders 請(qǐng)求表頭的類字典對(duì)象。 就像一個(gè)不區(qū)分大小寫的字典,帶有用于重復(fù)標(biāo)題的附加方法。
  • ?body?:請(qǐng)求正文(如果存在)作為字節(jié)字符串。
  • ?remote_ip?:客戶端的 IP 地址作為字符串。 如果設(shè)置了 HTTPServer.xheaders,將在 X-Real-Ip 或 X-Forwarded-For 標(biāo)頭中傳遞負(fù)載均衡器提供的真實(shí) IP 地址。
  • protocol
  • ?:使用的協(xié)議,“http”或“https”。 如果設(shè)置了 HTTPServer.xheaders,如果通過 X-Scheme 表頭報(bào)告,將傳遞負(fù)載均衡器使用的協(xié)議。
  • ?host?:請(qǐng)求的主機(jī)名,通常取自 Host 表頭。
  • ?arguments?:GET/POST 參數(shù)在 arguments 屬性中可用,它將參數(shù)名稱映射到值列表(以支持單個(gè)名稱的多個(gè)值)。 名稱是 str 類型,而參數(shù)是字節(jié)字符串。 請(qǐng)注意,這與 RequestHandler.get_argument 不同,后者將參數(shù)值作為 unicode 字符串返回。
  • ?query_arguments?:與參數(shù)的格式相同,但僅包含從查詢字符串中提取的參數(shù)。
  • ?body_arguments?:與參數(shù)格式相同,但僅包含從請(qǐng)求正文中提取的參數(shù)。
  • ?files?:文件上傳可在 files 屬性中使用,它將文件名映射到 HTTPFile 列表。
  • ?connectionHTTP?:請(qǐng)求附加到單個(gè) HTTP 連接,可以通過“connection”屬性訪問。 由于連接通常在 HTTP/1.1 中保持打開狀態(tài),因此可以在單個(gè)連接上按順序處理多個(gè)請(qǐng)求。
  • ?cookies?:http.cookies.Morsel 對(duì)象的字典。
  • ?full_url() → str?:[source]重構(gòu)此請(qǐng)求的完整 URL。
  • ?request_time() → float?:[source]返回此請(qǐng)求執(zhí)行所花費(fèi)的時(shí)間。
  • ?get_ssl_certificate(binary_form: bool = False) → Union[None, Dict[KT, VT], bytes]?:返回客戶端的 SSL 證書(如果有)。

要使用客戶端證書,必須設(shè)置 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)

默認(rèn)情況下,返回值是一個(gè)字典(如果沒有客戶端證書,則返回 None)。 如果 binary_form 為真,則改為返回 DER 編碼形式的證書。

exception tornado.httputil.HTTPInputError

來自遠(yuǎn)程源的格式錯(cuò)誤的HTTP請(qǐng)求或響應(yīng)的異常類。

exception tornado.httputil.HTTPOutputError

HTTP 輸出中的錯(cuò)誤的異常類。

class tornado.httputil.HTTPServerConnectionDelegate

實(shí)現(xiàn)這個(gè)接口來處理來自 HTTPServer 的請(qǐng)求。

start_request(server_conn: object, request_conn: tornado.httputil.HTTPConnection) → tornado.httputil.HTTPMessageDelegate

當(dāng)新請(qǐng)求開始時(shí),服務(wù)器會(huì)調(diào)用此方法。

參數(shù):

?server_conn ?– 是一個(gè)不透明的對(duì)象,表示長(zhǎng)生命(例如 tcp 級(jí)別)連接。

?request_conn? – 是單個(gè)請(qǐng)求/響應(yīng)交換的 HTTPConnection 對(duì)象。

此方法應(yīng)返回 ?HTTPMessageDelegate?。

on_close(server_conn: object) → None

當(dāng)連接關(guān)閉時(shí)調(diào)用此方法。

參數(shù): ?

server_conn ?– 是先前已傳遞給 start_request 的服務(wù)器連接。

class tornado.httputil.HTTPMessageDelegate

實(shí)現(xiàn)此接口以處理 HTTP 請(qǐng)求或響應(yīng)。

headers_received(start_line: Union[RequestStartLine, ResponseStartLine], headers: tornado.httputil.HTTPHeaders) → Optional[Awaitable[None]]

在接收并解析 HTTP 表頭時(shí)調(diào)用。

參數(shù):

?start_line ?– RequestStartLine 或 ResponseStartLine 取決于這是客戶端消息還是服務(wù)器消息。

?headers?——一個(gè) HTTPHeaders 實(shí)例。

某些 HTTPConnection 方法只能在 ?headers_received ?期間調(diào)用。

可能返回一個(gè) ?Future?; 如果確實(shí)如此,則在完成之前不會(huì)讀取正文。

data_received(chunk: bytes) → Optional[Awaitable[None]]

當(dāng)收到一大塊數(shù)據(jù)時(shí)調(diào)用。

可能會(huì)返回 ?Future ?進(jìn)行流量控制。

finish() → None

在收到最后一塊數(shù)據(jù)后調(diào)用。

on_connection_close() → None

如果連接在未完成請(qǐng)求的情況下關(guān)閉,則調(diào)用。

如果 ?headers_received ?被調(diào)用,?finish ?或 ?on_connection_close ?將被調(diào)用,但不會(huì)同時(shí)調(diào)用。

class tornado.httputil.HTTPConnection

應(yīng)用程序使用此接口來編寫它們的響應(yīng)。

write_headers(start_line: Union[RequestStartLine, ResponseStartLine], headers: tornado.httputil.HTTPHeaders, chunk: Optional[bytes] = None) → Future[None]

編寫一個(gè) HTTP 標(biāo)頭塊。

參數(shù):

?start_line ?– RequestStartLine 或 ResponseStartLine。

?headers?——一個(gè) HTTPHeaders 實(shí)例。

?chunk ?– 第一個(gè)(可選)數(shù)據(jù)塊。 這是一種優(yōu)化,以便可以在與標(biāo)題相同的調(diào)用中寫入小的響應(yīng)。

?start_line的版本字段被忽略。

返回一個(gè)用于流控制的 future。

在 6.0 版更改: ?callback?參數(shù)已刪除。

write(chunk: bytes) → Future[None]

寫入一大塊正文數(shù)據(jù)。

返回一個(gè)用于流控制的 future。

在 6.0 版更改: ?callback?參數(shù)已刪除。

finish() → None

表示最后的正文數(shù)據(jù)已被寫入。

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

無論 url 是否具有現(xiàn)有查詢參數(shù),都將 url 和參數(shù)連接起來。

?args可以是字典或鍵值對(duì)列表,后者允許具有相同鍵的多個(gè)值。

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

表示通過表單上傳的文件。

為了向后兼容,它的實(shí)例屬性也可以作為字典鍵訪問。

  • ?filename?
  • ?body?
  • ?content_type?

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

解析表單請(qǐng)求正文。

支持 ?application/x-www-form-urlencoded? 和 ?multipart/form-data?。 ?content_type ?參數(shù)應(yīng)該是一個(gè)字符串,?body ?應(yīng)該是一個(gè)字節(jié)字符串。 ?arguments ?和 ?files ?參數(shù)是字典,將使用解析的內(nèi)容進(jìn)行更新。

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

解析多部分/表單數(shù)據(jù)主體。

邊界和數(shù)據(jù)參數(shù)都是字節(jié)串。 ?arguments ?和 ?files ?參數(shù)中給出的字典將使用正文的內(nèi)容進(jìn)行更新。

在 5.1 版更改: 現(xiàn)在可以識(shí)別 RFC 2231/5987 (?filename*=?) 格式的非 ASCII 文件名。

tornado.httputil.format_timestamp(ts: Union[int, float, tuple, time.struct_time, datetime.datetime]) → str

以 HTTP 使用的格式格式化時(shí)間戳。

參數(shù)可以是 ?time.time? 返回的數(shù)字時(shí)間戳、?time.gmtime? 返回的時(shí)間元組或 ?datetime.datetime? 對(duì)象。

>>> format_timestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'

class tornado.httputil.RequestStartLine

RequestStartLine(method、path、version)
創(chuàng)建 RequestStartLine 的新實(shí)例(method、path、version)
?method?:字段編號(hào) 0 的別名
?path?:字段編號(hào) 1 的別名
?version?:字段編號(hào) 2 的別名

tornado.httputil.parse_request_start_line(line: str) → tornado.httputil.RequestStartLine

返回 HTTP 1.x 請(qǐng)求行的(method、path、version)元組。
響應(yīng)是一個(gè) ?collections.namedtuple?。

>>> parse_request_start_line("GET /foo HTTP/1.1")
RequestStartLine(method='GET', path='/foo', version='HTTP/1.1')

class tornado.httputil.ResponseStartLine

ResponseStartLine(version、code、reason)
創(chuàng)建 ResponseStartLine(version、code、reason)的新實(shí)例
?code?:字段編號(hào) 1 的別名
?reason?:字段編號(hào) 2 的別名
?version?:字段編號(hào) 0 的別名

tornado.httputil.parse_response_start_line(line: str) → tornado.httputil.ResponseStartLine

返回 HTTP 1.x 響應(yīng)行的(version、code、reason)元組。
響應(yīng)是一個(gè)? 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 身份驗(yàn)證使用的格式對(duì)用戶名/密碼對(duì)進(jìn)行編碼。

返回值是格式為 ?username:password? 的字節(jié)字符串。

tornado.httputil.split_host_and_port(netloc: str) → Tuple[str, Optional[int]]

從 ?netloc ?返回 ?(host, port)? 元組。

如果不存在,則返回的?port?將為 ?None?。

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

生成器將 ?parse_qs? 的結(jié)果轉(zhuǎn)換回名稱-值對(duì)。

tornado.httputil.parse_cookie(cookie: str) → Dict[str, str]

將 ?CookieHTTP 表頭解析為名稱/值對(duì)的字典。

該函數(shù)試圖模仿瀏覽器 cookie 解析行為; 它特別不遵循任何與 cookie 相關(guān)的 RFC(因?yàn)闉g覽器也不遵循)。

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


以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)