tornado.web — RequestHandler and Application classes
tornado.web — RequestHandler and Application classes
tornado.web provides a simple web framework with asynchronous features that allow it to scale to large numbers of open connections, making it ideal for long polling.
Here is a simple “Hello, world” example app:
import asyncio
import tornado
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
async def main():
application = tornado.web.Application([
(r"/", MainHandler),
])
application.listen(8888)
await asyncio.Event().wait()
if __name__ == "__main__":
asyncio.run(main())
See the User’s guide for additional information.
Thread-safety notes
In general, methods on RequestHandler and elsewhere in Tornado are not thread-safe. In particular, methods such as write(), finish(), and flush() must only be called from the main thread. If you use multiple threads it is important to use IOLoop.add_callback to transfer control back to the main thread before finishing the request, or to limit your use of other threads to IOLoop.run_in_executor and ensure that your callbacks running in the executor do not refer to Tornado objects.
Request handlers
class tornado.web.RequestHandler(…)[source]
Base class for HTTP request handlers.
Subclasses must define at least one of the methods defined in the “Entry points” section below.
Applications should not construct RequestHandler objects directly and subclasses should not override __init__ (override initialize instead).
Entry points
RequestHandler.initialize() → None
Hook for subclass initialization. Called for each request.
A dictionary passed as the third argument of a URLSpec will be supplied as keyword arguments to initialize().
Example:
class ProfileHandler(RequestHandler):
def initialize(self, database):
self.database = database
def get(self, username):
...
app = Application([
(r'/user/(.*)', ProfileHandler, dict(database=database)),
])
RequestHandler.prepare() → Awaitable[None] | None[source]
Called at the beginning of a request before get/post/etc.
Override this method to perform common initialization regardless of the request method. There is no guarantee that prepare will be called if an error occurs that is handled by the framework.
Asynchronous support: Use async def or decorate this method with gen.coroutine to make it asynchronous. If this method returns an Awaitable execution will not proceed until the Awaitable is done.
Added in version 3.1: Asynchronous support.
RequestHandler.on_finish() → None[source]
Called after the end of a request.
Override this method to perform cleanup, logging, etc. This method is primarily intended as a counterpart to prepare. However, there are a few error cases where on_finish may be called when prepare has not. (These are considered bugs and may be fixed in the future, but for now you may need to check to see if the initialization work done in prepare has occurred)
on_finish may not produce any output, as it is called after the response has been sent to the client.
Implement any of the following methods (collectively known as the HTTP verb methods) to handle the corresponding HTTP method. These methods can be made asynchronous with the async def keyword or gen.coroutine decorator.
The arguments to these methods come from the URLSpec: Any capturing groups in the regular expression become arguments to the HTTP verb methods (keyword arguments if the group is named, positional arguments if it’s unnamed).
To support a method not on this list, override the class variable SUPPORTED_METHODS:
class WebDAVHandler(RequestHandler):
SUPPORTED_METHODS = RequestHandler.SUPPORTED_METHODS + ('PROPFIND',)
def propfind(self):
pass
RequestHandler.get(_ args: str ,_ *kwargs: str) → None
RequestHandler.head(_ args: str ,_ *kwargs: str) → None
RequestHandler.post(_ args: str ,_ *kwargs: str) → None
RequestHandler.delete(_ args: str ,_ *kwargs: str) → None
RequestHandler.patch(_ args: str ,_ *kwargs: str) → None
RequestHandler.put(_ args: str ,_ *kwargs: str) → None
RequestHandler.options(_ args: str ,_ *kwargs: str) → None
Input
The argument methods provide support for HTML form-style arguments. These methods are available in both singular and plural forms because HTML forms are ambiguous and do not distinguish between a singular argument and a list containing one entry. If you wish to use other formats for arguments (for example, JSON), parse self.request.body yourself:
def prepare(self):
if self.request.headers['Content-Type'] == 'application/x-json':
self.args = json_decode(self.request.body)
# Access self.args directly instead of using self.get_argument.
RequestHandler.get_argument(name:str, default:str, strip:bool = True) → str[source]
RequestHandler.get_argument(name:str, default: _ArgDefaultMarker = _ARG_DEFAULT , strip:bool = True) → str
RequestHandler.get_argument(name:str, default:None, strip:bool = True) → str | None
Returns the value of the argument with the given name.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the request more than once, we return the last value.
This method searches both the query and body arguments.
RequestHandler.get_arguments(name:str, strip:bool = True) → List[str][source]
Returns a list of the arguments with the given name.
If the argument is not present, returns an empty list.
This method searches both the query and body arguments.
RequestHandler.get_query_argument(name:str, default:str, strip:bool = True) → str[source]
RequestHandler.get_query_argument(name:str, default: _ArgDefaultMarker = _ARG_DEFAULT , strip:bool = True) → str
RequestHandler.get_query_argument(name:str, default:None, strip:bool = True) → str | None
Returns the value of the argument with the given name from the request query string.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the url more than once, we return the last value.
Added in version 3.2.
RequestHandler.get_query_arguments(name:str, strip:bool = True) → List[str][source]
Returns a list of the query arguments with the given name.
If the argument is not present, returns an empty list.
Added in version 3.2.
RequestHandler.get_body_argument(name:str, default:str, strip:bool = True) → str[source]
RequestHandler.get_body_argument(name:str, default: _ArgDefaultMarker = _ARG_DEFAULT , strip:bool = True) → str
RequestHandler.get_body_argument(name:str, default:None, strip:bool = True) → str | None
Returns the value of the argument with the given name from the request body.
If default is not provided, the argument is considered to be required, and we raise a MissingArgumentError if it is missing.
If the argument appears in the url more than once, we return the last value.
Added in version 3.2.
RequestHandler.get_body_arguments(name:str, strip:bool = True) → List[str][source]
Returns a list of the body arguments with the given name.
If the argument is not present, returns an empty list.
Added in version 3.2.
RequestHandler.decode_argument(value:bytes, name:str | None = None) → str[source]
Decodes an argument from the request.
The argument has been percent-decoded and is now a byte string. By default, this method decodes the argument as utf-8 and returns a unicode string, but this may be overridden in subclasses.
This method is used as a filter for both get_argument() and for values extracted from the url and passed to get()/post()/etc.
The name of the argument is provided if known, but may be None (e.g. for unnamed groups in the url regex).
RequestHandler.request
The tornado.httputil.HTTPServerRequest object containing additional request parameters including e.g. headers and body data.
RequestHandler.path_args
RequestHandler.path_kwargs
The path_args and path_kwargs attributes contain the positional and keyword arguments that are passed to the HTTP verb methods. These attributes are set before those methods are called, so the values are available during prepare.
RequestHandler.data_received(chunk:bytes) → Awaitable[None] | None[source]
Implement this method to handle streamed request data.
Requires the stream_request_body decorator.
May be a coroutine for flow control.
Output
RequestHandler.set_status(status_code:int, reason:str | None = None) → None[source]
Sets the status code for our response.
-
Parameters:
-
status_code (int) – Response status code.
-
reason (str) – Human-readable reason phrase describing the status code. If
None, it will be filled in from http.client.responses or “Unknown”.
-
Changed in version 5.0: No longer validates that the response code is in http.client.responses.
RequestHandler.set_header(name:str, value:bytes | str | int | Integral | datetime) → None[source]
Sets the given response header name and value.
All header values are converted to strings (datetime objects are formatted according to the HTTP specification for the Date header).
RequestHandler.add_header(name:str, value:bytes | str | int | Integral | datetime) → None[source]
Adds the given response header and value.
Unlike set_header, add_header may be called multiple times to return multiple values for the same header.
RequestHandler.clear_header(name:str) → None[source]
Clears an outgoing header, undoing a previous set_header call.
Note that this method does not apply to multi-valued headers set by add_header.
RequestHandler.set_default_headers() → None[source]
Override this to set HTTP headers at the beginning of the request.
For example, this is the place to set a custom Server header. Note that setting such headers in the normal flow of request processing may not do what you want, since headers may be reset during error handling.
RequestHandler.write(chunk:str | bytes | dict) → None[source]
Writes the given chunk to the output buffer.
To write the output to the network, use the flush() method below.
If the given chunk is a dictionary, we write it as JSON and set the Content-Type of the response to be application/json. (if you want to send JSON as a different Content-Type, call set_header after calling write()).
Note that lists are not converted to JSON because of a potential cross-site security vulnerability. All JSON output should be wrapped in a dictionary. More details at <http://haacked.com/archive/2009/06/25/json-hijacking.aspx/> and <https://github.com/facebook/tornado/issues/1009>
RequestHandler.flush(include_footers:bool = False) → Future[None][source]
Flushes the current output buffer to the network.
Changed in version 4.0: Now returns a Future if no callback is given.
Changed in version 6.0: The callback argument was removed.
RequestHandler.finish(chunk:str | bytes | dict | None = None) → Future[None][source]
Finishes this response, ending the HTTP request.
Passing a chunk to finish() is equivalent to passing that chunk to write() and then calling finish() with no arguments.
Returns a Future which may optionally be awaited to track the sending of the response to the client. This Future resolves when all the response data has been sent, and raises an error if the connection is closed before all data can be sent.
Changed in version 5.1: Now returns a Future instead of None.
RequestHandler.render(template_name:str, __ kwargs: Any) → Future[None][source]
Renders the template with the given arguments as the response.
render() calls finish(), so no other output methods can be called after it.
Returns a Future with the same semantics as the one returned by finish. Awaiting this Future is optional.
Changed in version 5.1: Now returns a Future instead of None.
RequestHandler.render_string(template_name:str, __ kwargs: Any) → bytes[source]
Generate the given template with the given arguments.
We return the generated byte string (in utf8). To generate and write a template as a response, use render() above.
RequestHandler.get_template_namespace() → Dict[str, Any][source]
Returns a dictionary to be used as the default template namespace.
May be overridden by subclasses to add or modify values.
The results of this method will be combined with additional defaults in the tornado.template module and keyword arguments to render or render_string.
RequestHandler.redirect(url:str, permanent:bool = False, status:int | None = None) → None[source]
Sends a redirect to the given (optionally relative) URL.
If the status argument is specified, that value is used as the HTTP status code; otherwise either 301 (permanent) or 302 (temporary) is chosen based on the permanent argument. The default is 302 (temporary).
RequestHandler.send_error(status_code:int = 500, __ kwargs: Any) → None[source]
Sends the given HTTP error code to the browser.
If flush() has already been called, it is not possible to send an error, so this method will simply terminate the response. If output has been written but not yet flushed, it will be discarded and replaced with the error page.
Override write_error() to customize the error page that is returned. Additional keyword arguments are passed through to write_error.
RequestHandler.write_error(status_code:int, __ kwargs: Any) → None[source]
Override to implement custom error pages.
write_error may call write, render, set_header, etc to produce output as usual.
If this error was caused by an uncaught exception (including HTTPError), an exc_info triple will be available as kwargs["exc_info"]. Note that this exception may not be the “current” exception for purposes of methods like sys.exc_info() or traceback.format_exc.
RequestHandler.clear() → None[source]
Resets all headers and content for this response.
RequestHandler.render_linked_js(js_files:Iterable[str]) → str[source]
Default method used to render the final js links for the rendered webpage.
Override this method in a sub-classed controller to change the output.
RequestHandler.render_embed_js(js_embed:Iterable[bytes]) → bytes[source]
Default method used to render the final embedded js for the rendered webpage.
Override this method in a sub-classed controller to change the output.
RequestHandler.render_linked_css(css_files:Iterable[str]) → str[source]
Default method used to render the final css links for the rendered webpage.
Override this method in a sub-classed controller to change the output.
RequestHandler.render_embed_css(css_embed:Iterable[bytes]) → bytes[source]
Default method used to render the final embedded css for the rendered webpage.
Override this method in a sub-classed controller to change the output.
(本文超出站点单文档体积上限,已按小节截断)
