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() → Optional[Awaitable[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.

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.

New 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 a counterpart to prepare. 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) → Optional[str]

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: Union[None, str, RAISE] = RAISE, strip:bool = True) → Optional[str][source]

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.

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

New in version 3.2.

RequestHandler.get_body_argument(name:str, default: Union[None, str, RAISE] = RAISE, strip:bool = True) → Optional[str][source]

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.

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

New in version 3.2.

RequestHandler.decode_argument(value:bytes, name:Optional[str] = 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) → Optional[Awaitable[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:Optional[str] = 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:Union[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:Union[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:Union[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:Optional[Union[str, bytes, dict]] = 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:Optional[int] = 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.

Cookies

RequestHandler.cookies

An alias for self.request.cookies.

RequestHandler.get_cookie(name:str, default:Optional[str] = None) → Optional[str][source]

Returns the value of the request cookie with the given name.

If the named cookie is not present, returns default.

This method only returns cookies that were present in the request. It does not see the outgoing cookies set by set_cookie in this handler.

RequestHandler.set_cookie(name:str, value:Union[str, bytes], domain:Optional[str] = None, expires:Optional[Union[float, Tuple, datetime]] = None, path:str = ‘/‘, expires_days:Optional[float] = None, _, max_age: Optional[int] = None , httponly: bool = False , secure: bool = False , samesite: Optional[str] = None ,_ kwargs: Any*) → None[source]

Sets an outgoing cookie name/value with the given options.

Newly-set cookies are not immediately visible via get_cookie; they are not present until the next request.

Most arguments are passed directly to http.cookies.Morsel directly. See <https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Set-Cookie> for more information.

expires may be a numeric timestamp as returned by time.time, a time tuple as returned by time.gmtime, or a datetime.datetime object. expires_days is provided as a convenience to set an expiration time in days from today (if both are set, expires is used).

Deprecated since version 6.3: Keyword arguments are currently accepted case-insensitively. In Tornado 7.0 this will be changed to only accept lowercase arguments.

RequestHandler.clear_cookie(name:str, __ kwargs: Any) → None[source]

Deletes the cookie with the given name.

This method accepts the same arguments as set_cookie, except for expires and max_age. Clearing a cookie requires the same domain and path arguments as when it was set. In some cases the samesite and secure arguments are also required to match. Other arguments are ignored.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does. The samesite and secure flags have recently become required for clearing samesite="none" cookies.

RequestHandler.clear_all_cookies(__ kwargs: Any) → None[source]

Attempt to delete all the cookies the user sent with this request.

See clear_cookie for more information on keyword arguments. Due to limitations of the cookie protocol, it is impossible to determine on the server side which values are necessary for the domain, path, samesite, or secure arguments, this method can only be successful if you consistently use the same values for these arguments when setting cookies.

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2: Added the path and domain parameters.

Changed in version 6.3: Now accepts all keyword arguments that set_cookie does.

Deprecated since version 6.3: The increasingly complex rules governing cookies have made it impossible for a clear_all_cookies method to work reliably since all we know about cookies are their names. Applications should generally use clear_cookie one at a time instead.

RequestHandler.get_signed_cookie(name:str, value:Optional[str] = None, max_age_days:float = 31, min_version:Optional[int] = None) → Optional[bytes][source]

Returns the given signed cookie if it validates, or None.

The decoded cookie value is returned as a byte string (unlike get_cookie).

Similar to get_cookie, this method only returns cookies that were present in the request. It does not see outgoing cookies set by set_signed_cookie in this handler.

Changed in version 3.2.1:

Added the min_version argument. Introduced cookie version 2; both versions 1 and 2 are accepted by default.

Changed in version 6.3: Renamed from get_secure_cookie to get_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

RequestHandler.get_signed_cookie_key_version(name:str, value:Optional[str] = None) → Optional[int][source]

Returns the signing key version of the secure cookie.

The version is returned as int.

Changed in version 6.3: Renamed from get_secure_cookie_key_version to set_signed_cookie_key_version to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

RequestHandler.set_signed_cookie(name:str, value:Union[str, bytes], expires_days:Optional[float] = 30, version:Optional[int] = None, __ kwargs: Any) → None[source]

Signs and timestamps a cookie so it cannot be forged.

You must specify the cookie_secret setting in your Application to use this method. It should be a long, random sequence of bytes to be used as the HMAC secret for the signature.

To read a cookie set with this method, use get_signed_cookie().

Note that the expires_days parameter sets the lifetime of the cookie in the browser, but is independent of the max_age_days parameter to get_signed_cookie. A value of None limits the lifetime to the current browser session.

Secure cookies may contain arbitrary byte values, not just unicode strings (unlike regular cookies)

Similar to set_cookie, the effect of this method will not be seen until the following request.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

Changed in version 6.3: Renamed from set_secure_cookie to set_signed_cookie to avoid confusion with other uses of “secure” in cookie attributes and prefixes. The old name remains as an alias.

RequestHandler.get_secure_cookie()

Deprecated alias for get_signed_cookie.

Deprecated since version 6.3.

RequestHandler.get_secure_cookie_key_version()

Deprecated alias for get_signed_cookie_key_version.

Deprecated since version 6.3.

RequestHandler.set_secure_cookie()

Deprecated alias for set_signed_cookie.

Deprecated since version 6.3.

RequestHandler.create_signed_value(name:str, value:Union[str, bytes], version:Optional[int] = None) → bytes[source]

Signs and timestamps a string so it cannot be forged.

Normally used via set_signed_cookie, but provided as a separate method for non-cookie uses. To decode a value not stored as a cookie use the optional value argument to get_signed_cookie.

Changed in version 3.2.1: Added the version argument. Introduced cookie version 2 and made it the default.

tornado.web.MIN_SUPPORTED_SIGNED_VALUE_VERSION = 1

The oldest signed value version supported by this version of Tornado.

Signed values older than this version cannot be decoded.

New in version 3.2.1.

tornado.web.MAX_SUPPORTED_SIGNED_VALUE_VERSION = 2

The newest signed value version supported by this version of Tornado.

Signed values newer than this version cannot be decoded.

New in version 3.2.1.

tornado.web.DEFAULT_SIGNED_VALUE_VERSION = 2

The signed value version produced by RequestHandler.create_signed_value.

May be overridden by passing a version keyword argument.

New in version 3.2.1.

tornado.web.DEFAULT_SIGNED_VALUE_MIN_VERSION = 1

The oldest signed value accepted by RequestHandler.get_signed_cookie.

May be overridden by passing a min_version keyword argument.

New in version 3.2.1.

(本文超出站点单文档体积上限,已按小节截断)