tornado.httputil — Manipulate HTTP headers and URLs¶
This module also defines the class which is exposedvia .
- class
tornado.httputil.
HTTPHeaders
(*args, **kwargs)[源代码]
A dictionary that maintainsHttp-Header-Case
for all keys.
Supports multiple values per key via a pair of new methods,add()
and . The regular dictionary interfacereturns a single value per key, with multiple values joined by acomma.- >>> h.add("Set-Cookie", "A=B")
>>> h.add("Set-Cookie", "C=D")
>>> h["set-cookie"]
'A=B,C=D'
>>> h.getlist("set-cookie")
['A=B', 'C=D']
add
(_name, value)[源代码]
Adds a new value for the given key.
getlist
(_name)[源代码]
Returns all values for the given header as a list.
getall
()[源代码]
Returns an iterable of all (name, value) pairs.
If a header has multiple values, multiple pairs will bereturned with the same name.
parse_line
(_line)[源代码]
Updates the dictionary with a single header line.
- _classmethod
parse
(headers)[源代码]
Returns a dictionary from HTTP header text.- >>> h = HTTPHeaders.parse("Content-Type: text/html\r\nContent-Length: 42\r\n")
>>> sorted(h.items())
[('Content-Length', '42'), ('Content-Type', 'text/html')]
- >>> h = HTTPHeaders.parse("Content-Type: text/html\r\nContent-Length: 42\r\n")
- >>> h.add("Set-Cookie", "A=B")
- class
tornado.httputil.
HTTPServerRequest
(method=None, uri=None, version='HTTP/1.0', headers=None, body=None, host=None, files=None, connection=None, start_line=None)[源代码]
A single HTTP request.
All attributes are typestr
unless otherwise noted.method
HTTP request method, e.g. “GET” or “POST”
uri
¶
The requested uri.
path
The path portion ofuri
query
The query portion ofuri
version
HTTP version specified in request, e.g. “HTTP/1.1”
headers
¶
dictionary-like object for request headers. Acts likea case-insensitive dictionary with additional methods for repeatedheaders.
body
¶
Request body, if present, as a byte string.
remote_ip
Client’s IP address as a string. IfHTTPServer.xheaders
is set,will pass along the real IP address provided by a load balancerin theX-Real-Ip
orX-Forwarded-For
header.
protocol
¶
The protocol used, either “http” or “https”. IfHTTPServer.xheaders
is set, will pass along the protocol used by a load balancer ifreported via anX-Scheme
header.
host
The requested hostname, usually taken from theHost
header.
arguments
¶
GET/POST arguments are available in the arguments property, whichmaps arguments names to lists of values (to support multiple valuesfor individual names). Names are of type , while argumentsare byte strings. Note that this is different fromRequestHandler.get_argument
, which returns argument values asunicode strings.
query_arguments
Same format asarguments
, but contains only arguments extractedfrom the query string.
3.2 新版功能.
body_arguments
¶
Same format asarguments
, but contains only arguments extractedfrom the request body.
3.2 新版功能.
files
File uploads are available in the files property, which maps filenames to lists ofHTTPFile
.
connection
An HTTP request is attached to a single HTTP connection, which canbe accessed through the “connection” attribute. Since connectionsare typically kept open in HTTP/1.1, multiple requests can be handledsequentially on a single connection.
在 4.0 版更改: Moved from
tornado.httpserver.HTTPRequest
.supportshttp_1_1
()[源代码]
Returns True if this request supports HTTP/1.1 semantics.
4.0 版后已移除: Applications are less likely to need this information with theintroduction of . If you still need it, accesstheversion
attribute directly.
A dictionary of Cookie.Morsel objects.
write
(_chunk, callback=None)[源代码]
Writes the given chunk to the response stream.
4.0 版后已移除: Userequest.connection
and theHTTPConnection
methodsto write the response.
finish
()¶
Finishes this HTTP request on the open connection.
4.0 版后已移除: Userequest.connection
and the methodsto write the response.
fullurl
()[源代码]
Reconstructs the full URL for this request.
request_time
()[源代码]
Returns the amount of time it took for this request to execute.
get_ssl_certificate
(_binary_form=False)[源代码]
Returns the client’s SSL certificate, if any.
To use client certificates, the HTTPServer’sssl.SSLContext.verify_mode
field must be set, e.g.:
By default, the return value is a dictionary (or None, if noclient certificate is present). Ifbinary_form
is true, aDER-encoded form of the certificate is returned instead. SeeSSLSocket.getpeercert() in the standard library for moredetails.
- _exception
tornado.httputil.
HTTPInputError
[源代码]
Exception class for malformed HTTP requests or responsesfrom remote sources.
4.0 新版功能.
- exception
tornado.httputil.
HTTPOutputError
[源代码]
Exception class for errors in HTTP output.
4.0 新版功能.
- class
tornado.httputil.
HTTPServerConnectionDelegate
[源代码]
Implement this interface to handle requests fromHTTPServer
.
4.0 新版功能.startrequest
(_server_conn, request_conn)¶
This method is called by the server when a new request has started.
|参数:
|——-
|
- server_conn – is an opaque object representing the long-lived(e.g. tcp-level) connection.
- request_conn – is a object for a singlerequest/response exchange.
This method should return aHTTPMessageDelegate
.
onclose
(_server_conn)¶
This method is called when a connection has been closed.
|参数:
|——-
|server_conn – is a server connection that has previously beenpassed tostartrequest
.
- _class
tornado.httputil.
HTTPMessageDelegate
¶
Implement this interface to handle an HTTP request or response.
4.0 新版功能.headersreceived
(_start_line, headers)¶
Called when the HTTP headers have been received and parsed.
|参数:
|——-
|
- start_line – a or ResponseStartLinedepending on whether this is a client or server message.
- headers – a instance.
SomeHTTPConnection
methods can only be called duringheadersreceived
.
May return a ; if it does the body will not be readuntil it is done.
data_received
(_chunk)[源代码]
Called when a chunk of data has been received.
May return aFuture
for flow control.
finish
()¶
Called after the last chunk of data has been received.
onconnection_close
()¶
Called if the connection is closed without finishing the request.
Ifheaders_received
is called, eitherfinish
oron_connection_close
will be called, but not both.
- _class
tornado.httputil.
HTTPConnection
¶
Applications use this interface to write their responses.
4.0 新版功能.writeheaders
(_start_line, headers, chunk=None, callback=None)¶
Write an HTTP header block.
|参数:
|——-
|
- start_line – a or ResponseStartLine.
- headers – a instance.
- chunk – the first (optional) chunk of data. This is an optimizationso that small responses can be written in the same call as theirheaders.
- callback – a callback to be run when the write is complete.
Theversion
field ofstartline
is ignored.
Returns aFuture
if no callback is given.
write
(_chunk, callback=None)¶
Writes a chunk of body data.
The callback will be run when the write is complete. If no callbackis given, returns a Future.
finish
()¶
Indicates that the last body data has been written.
tornado.httputil.
(_url, args)¶
Concatenate url and arguments regardless of whetherurl has existing query parameters.args
may be either a dictionary or a list of key-value pairs(the latter allows for multiple values with the same key.
- _class
tornado.httputil.
HTTPFile
¶
Represents a file uploaded via a form.
For backwards compatibility, its instance attributes are alsoaccessible as dictionary keys.
- filename
- body
- contenttype
tornado.httputil.
parse_body_arguments
(_content_type, body, arguments, files, headers=None)¶
Parses a form request body.
Supportsapplication/x-www-form-urlencoded
andmultipart/form-data
. Thecontenttype
parameter should bea string andbody
should be a byte string. Thearguments
andfiles
parameters are dictionaries that will be updatedwith the parsed contents.
tornado.httputil.
parse_multipart_form_data
(_boundary, data, arguments, files)¶
Parses amultipart/form-data
body.
Theboundary
anddata
parameters are both byte strings.The dictionaries given in the arguments and files parameterswill be updated with the contents of the body.
tornado.httputil.
formattimestamp
(_ts)¶
Formats a timestamp in the format used by HTTP.
The argument may be a numeric timestamp as returned by ,a time tuple as returned bytime.gmtime
, or a object.- >>> formattimestamp(1359312200)
'Sun, 27 Jan 2013 18:43:20 GMT'
- >>> formattimestamp(1359312200)
- _class
tornado.httputil.
RequestStartLine
¶
RequestStartLine(method, path, version)method
Alias for field number 0
path
¶
Alias for field number 1
version
Alias for field number 2
tornado.httputil.
parserequest_start_line
(_line)[源代码]
Returns a (method, path, version) tuple for an HTTP 1.x request line.
The response is acollections.namedtuple
.
- _class
tornado.httputil.
ResponseStartLine
ResponseStartLine(version, code, reason)code
¶
Alias for field number 1
reason
Alias for field number 2
version
¶
Alias for field number 0
tornado.httputil.
parseresponse_start_line
(_line)¶
Returns a (version, code, reason) tuple for an HTTP 1.x response line.
The response is a .
tornado.httputil.
split_host_and_port
(_netloc)[源代码]
Returns(host, port)
tuple fromnetloc
.
Returnedport
will beNone
if not present.
4.1 新版功能.
Parse aCookie
HTTP header into a dict of name/value pairs.
This function attempts to mimic browser cookie parsing behavior;it specifically does not follow any of the cookie-related RFCs(because browsers don’t either).
The algorithm used is identical to that used by Django version 1.9.10.
4.4.2 新版功能.