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 tornado.ioloop
import tornado.web
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
if __name__ == "__main__":
application = tornado.web.Application([
(r"/", MainHandler),
])
application.listen(8888)
tornado.ioloop.IOLoop.current().start()
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__
(overrideinitialize
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 toinitialize()
.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 withgen.coroutine
to make it asynchronous. If this method returns anAwaitable
execution will not proceed until theAwaitable
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, **kwargs) → None¶
-
RequestHandler.
head
(*args, **kwargs) → None¶
-
RequestHandler.
post
(*args, **kwargs) → None¶
-
RequestHandler.
delete
(*args, **kwargs) → None¶
-
RequestHandler.
patch
(*args, **kwargs) → None¶
-
RequestHandler.
put
(*args, **kwargs) → None¶
-
RequestHandler.
options
(*args, **kwargs) → 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: Union[None, str, RAISE] = RAISE, strip: bool = True) → Optional[str][source]¶ 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 toget()
/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
andpath_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 duringprepare
.
-
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 fromhttp.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, numbers.Integral, datetime.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 theDate
header).
-
RequestHandler.
add_header
(name: str, value: Union[bytes, str, int, numbers.Integral, datetime.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 differentContent-Type
, callset_header
after callingwrite()
).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: Union[str, bytes, dict, None] = None) → Future[None][source]¶ Finishes this response, ending the HTTP request.
Passing a
chunk
tofinish()
is equivalent to passing that chunk towrite()
and then callingfinish()
with no arguments.Returns a
Future
which may optionally be awaited to track the sending of the response to the client. ThisFuture
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 ofNone
.
-
RequestHandler.
render
(template_name: str, **kwargs) → Future[None][source]¶ Renders the template with the given arguments as the response.
render()
callsfinish()
, so no other output methods can be called after it.Returns a
Future
with the same semantics as the one returned byfinish
. Awaiting thisFuture
is optional.Changed in version 5.1: Now returns a
Future
instead ofNone
.
-
RequestHandler.
render_string
(template_name: str, **kwargs) → 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 torender
orrender_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 thepermanent
argument. The default is 302 (temporary).
-
RequestHandler.
send_error
(status_code: int = 500, **kwargs) → 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 towrite_error
.
-
RequestHandler.
write_error
(status_code: int, **kwargs) → None[source]¶ Override to implement custom error pages.
write_error
may callwrite
,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 askwargs["exc_info"]
. Note that this exception may not be the “current” exception for purposes of methods likesys.exc_info()
ortraceback.format_exc
.
-
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.
Cookies¶
An alias for
self.request.cookies
.
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.
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.expires may be a numeric timestamp as returned by
time.time
, a time tuple as returned bytime.gmtime
, or adatetime.datetime
object.Additional keyword arguments are set on the cookies.Morsel directly. See https://docs.python.org/3/library/http.cookies.html#http.cookies.Morsel for available attributes.
Deletes the cookie with the given name.
Due to limitations of the cookie protocol, you must pass the same path and domain to clear a cookie as were used when that cookie was set (but there is no way to find out on the server side which values were used for a given cookie).
Similar to
set_cookie
, the effect of this method will not be seen until the following request.
Deletes all the cookies the user sent with this request.
See
clear_cookie
for more information on the path and domain parameters.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
anddomain
parameters.
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 byset_secure_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.
Returns the signing key version of the secure cookie.
The version is returned as int.
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_secure_cookie()
.Note that the
expires_days
parameter sets the lifetime of the cookie in the browser, but is independent of themax_age_days
parameter toget_secure_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.
-
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_secure_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_secure_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_secure_cookie
.May be overridden by passing a
min_version
keyword argument.New in version 3.2.1.
Other¶
-
RequestHandler.
application
¶ The
Application
object serving this request
-
RequestHandler.
check_etag_header
() → bool[source]¶ Checks the
Etag
header against requests’sIf-None-Match
.Returns
True
if the request’s Etag matches and a 304 should be returned. For example:self.set_etag_header() if self.check_etag_header(): self.set_status(304) return
This method is called automatically when the request is finished, but may be called earlier for applications that override
compute_etag
and want to do an early check forIf-None-Match
before completing the request. TheEtag
header should be set (perhaps withset_etag_header
) before calling this method.
Verifies that the
_xsrf
cookie matches the_xsrf
argument.To prevent cross-site request forgery, we set an
_xsrf
cookie and include the same value as a non-cookie field with allPOST
requests. If the two do not match, we reject the form submission as a potential forgery.The
_xsrf
value may be set as either a form field named_xsrf
or in a custom HTTP header namedX-XSRFToken
orX-CSRFToken
(the latter is accepted for compatibility with Django).See http://en.wikipedia.org/wiki/Cross-site_request_forgery
Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.
-
RequestHandler.
compute_etag
() → Optional[str][source]¶ Computes the etag header to be used for this request.
By default uses a hash of the content written so far.
May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.
-
RequestHandler.
create_template_loader
(template_path: str) → tornado.template.BaseLoader[source]¶ Returns a new template loader for the given path.
May be overridden by subclasses. By default returns a directory-based loader on the given path, using the
autoescape
andtemplate_whitespace
application settings. If atemplate_loader
application setting is supplied, uses that instead.
-
RequestHandler.
current_user
¶ The authenticated user for this request.
This is set in one of two ways:
A subclass may override
get_current_user()
, which will be called automatically the first timeself.current_user
is accessed.get_current_user()
will only be called once per request, and is cached for future access:def get_current_user(self): user_cookie = self.get_secure_cookie("user") if user_cookie: return json.loads(user_cookie) return None
It may be set as a normal variable, typically from an overridden
prepare()
:@gen.coroutine def prepare(self): user_id_cookie = self.get_secure_cookie("user_id") if user_id_cookie: self.current_user = yield load_user(user_id_cookie)
Note that
prepare()
may be a coroutine whileget_current_user()
may not, so the latter form is necessary if loading the user requires asynchronous operations.The user object may be any type of the application’s choosing.
-
RequestHandler.
detach
() → tornado.iostream.IOStream[source]¶ Take control of the underlying stream.
Returns the underlying
IOStream
object and stops all further HTTP processing. Intended for implementing protocols like websockets that tunnel over an HTTP handshake.This method is only supported when HTTP/1.1 is used.
New in version 5.1.
-
RequestHandler.
get_browser_locale
(default: str = 'en_US') → tornado.locale.Locale[source]¶ Determines the user’s locale from
Accept-Language
header.See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
-
RequestHandler.
get_current_user
() → Any[source]¶ Override to determine the current user from, e.g., a cookie.
This method may not be a coroutine.
-
RequestHandler.
get_login_url
() → str[source]¶ Override to customize the login URL based on the request.
By default, we use the
login_url
application setting.
-
RequestHandler.
get_template_path
() → Optional[str][source]¶ Override to customize template path for each handler.
By default, we use the
template_path
application setting. Return None to load templates relative to the calling file.
-
RequestHandler.
get_user_locale
() → Optional[tornado.locale.Locale][source]¶ Override to determine the locale from the authenticated user.
If None is returned, we fall back to
get_browser_locale()
.This method should return a
tornado.locale.Locale
object, most likely obtained via a call liketornado.locale.get("en")
-
RequestHandler.
locale
¶ The locale for the current session.
Determined by either
get_user_locale
, which you can override to set the locale based on, e.g., a user preference stored in a database, orget_browser_locale
, which uses theAccept-Language
header.
-
RequestHandler.
log_exception
(typ: Optional[Type[BaseException]], value: Optional[BaseException], tb: Optional[traceback]) → None[source]¶ Override to customize logging of uncaught exceptions.
By default logs instances of
HTTPError
as warnings without stack traces (on thetornado.general
logger), and all other exceptions as errors with stack traces (on thetornado.application
logger).New in version 3.1.
-
RequestHandler.
on_connection_close
() → None[source]¶ Called in async handlers if the client closed the connection.
Override this to clean up resources associated with long-lived connections. Note that this method is called only if the connection was closed during asynchronous processing; if you need to do cleanup after every request override
on_finish
instead.Proxies may keep a connection open for a time (perhaps indefinitely) after the client has gone away, so this method may not be called promptly after the end user closes their connection.
-
RequestHandler.
require_setting
(name: str, feature: str = 'this feature') → None[source]¶ Raises an exception if the given app setting is not defined.
-
RequestHandler.
reverse_url
(name: str, *args) → str[source]¶ Alias for
Application.reverse_url
.
-
RequestHandler.
set_etag_header
() → None[source]¶ Sets the response’s Etag header using
self.compute_etag()
.Note: no header will be set if
compute_etag()
returnsNone
.This method is called automatically when the request is finished.
-
RequestHandler.
settings
¶ An alias for
self.application.settings
.
-
RequestHandler.
static_url
(path: str, include_host: Optional[bool] = None, **kwargs) → str[source]¶ Returns a static URL for the given relative static file path.
This method requires you set the
static_path
setting in your application (which specifies the root directory of your static files).This method returns a versioned url (by default appending
?v=<signature>
), which allows the static files to be cached indefinitely. This can be disabled by passinginclude_version=False
(in the default implementation; other static file implementations are not required to support this, but they may support other options).By default this method returns URLs relative to the current host, but if
include_host
is true the URL returned will be absolute. If this handler has aninclude_host
attribute, that value will be used as the default for allstatic_url
calls that do not passinclude_host
as a keyword argument.
-
RequestHandler.
xsrf_form_html
() → str[source]¶ An HTML
<input/>
element to be included with all POST forms.It defines the
_xsrf
input value, which we check on all POST requests to prevent cross-site request forgery. If you have set thexsrf_cookies
application setting, you must include this HTML within all of your HTML forms.In a template, this method should be called with
{% module xsrf_form_html() %}
See
check_xsrf_cookie()
above for more information.
-
RequestHandler.
xsrf_token
¶ The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an ‘_xsrf’ cookie and include the same ‘_xsrf’ value as an argument with all POST requests. If the two do not match, we reject the form submission as a potential forgery.
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
This property is of type
bytes
, but it contains only ASCII characters. If a character string is required, there is no need to base64-encode it; just decode the byte string as UTF-8.Changed in version 3.2.2: The xsrf token will now be have a random mask applied in every request, which makes it safe to include the token in pages that are compressed. See http://breachattack.com for more information on the issue fixed by this change. Old (version 1) cookies will be converted to version 2 when this method is called unless the
xsrf_cookie_version
Application
setting is set to 1.Changed in version 4.3: The
xsrf_cookie_kwargs
Application
setting may be used to supply additional cookie options (which will be passed directly toset_cookie
). For example,xsrf_cookie_kwargs=dict(httponly=True, secure=True)
will set thesecure
andhttponly
flags on the_xsrf
cookie.
Application configuration¶
-
class
tornado.web.
Application
(handlers: Optional[List[Union[Rule, Tuple]]] = None, default_host: Optional[str] = None, transforms: Optional[List[Type[OutputTransform]]] = None, **settings)[source]¶ A collection of request handlers that make up a web application.
Instances of this class are callable and can be passed directly to HTTPServer to serve the application:
application = web.Application([ (r"/", MainPageHandler), ]) http_server = httpserver.HTTPServer(application) http_server.listen(8080) ioloop.IOLoop.current().start()
The constructor for this class takes in a list of
Rule
objects or tuples of values corresponding to the arguments ofRule
constructor:(matcher, target, [target_kwargs], [name])
, the values in square brackets being optional. The default matcher isPathMatches
, so(regexp, target)
tuples can also be used instead of(PathMatches(regexp), target)
.A common routing target is a
RequestHandler
subclass, but you can also use lists of rules as a target, which create a nested routing configuration:application = web.Application([ (HostMatches("example.com"), [ (r"/", MainPageHandler), (r"/feed", FeedHandler), ]), ])
In addition to this you can use nested
Router
instances,HTTPMessageDelegate
subclasses and callables as routing targets (seerouting
module docs for more information).When we receive requests, we iterate over the list in order and instantiate an instance of the first request class whose regexp matches the request path. The request class can be specified as either a class object or a (fully-qualified) name.
A dictionary may be passed as the third element (
target_kwargs
) of the tuple, which will be used as keyword arguments to the handler’s constructor andinitialize
method. This pattern is used for theStaticFileHandler
in this example (note that aStaticFileHandler
can be installed automatically with the static_path setting described below):application = web.Application([ (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}), ])
We support virtual hosts with the
add_handlers
method, which takes in a host regular expression as the first argument:application.add_handlers(r"www\.myhost\.com", [ (r"/article/([0-9]+)", ArticleHandler), ])
If there’s no match for the current request’s host, then
default_host
parameter value is matched against host regular expressions.Warning
Applications that do not use TLS may be vulnerable to DNS rebinding attacks. This attack is especially relevant to applications that only listen on
127.0.0.1
or other private networks. Appropriate host patterns must be used (instead of the default ofr'.*'
) to prevent this risk. Thedefault_host
argument must not be used in applications that may be vulnerable to DNS rebinding.You can serve static files by sending the
static_path
setting as a keyword argument. We will serve those files from the/static/
URI (this is configurable with thestatic_url_prefix
setting), and we will serve/favicon.ico
and/robots.txt
from the same directory. A custom subclass ofStaticFileHandler
can be specified with thestatic_handler_class
setting.Changed in version 4.5: Integration with the new
tornado.routing
module.-
settings
¶ Additional keyword arguments passed to the constructor are saved in the
settings
dictionary, and are often referred to in documentation as “application settings”. Settings are used to customize various aspects of Tornado (although in some cases richer customization is possible by overriding methods in a subclass ofRequestHandler
). Some applications also like to use thesettings
dictionary as a way to make application-specific settings available to handlers without using global variables. Settings used in Tornado are described below.General settings:
autoreload
: IfTrue
, the server process will restart when any source files change, as described in Debug mode and automatic reloading. This option is new in Tornado 3.2; previously this functionality was controlled by thedebug
setting.debug
: Shorthand for several debug mode settings, described in Debug mode and automatic reloading. Settingdebug=True
is equivalent toautoreload=True
,compiled_template_cache=False
,static_hash_cache=False
,serve_traceback=True
.default_handler_class
anddefault_handler_args
: This handler will be used if no other match is found; use this to implement custom 404 pages (new in Tornado 3.2).compress_response
: IfTrue
, responses in textual formats will be compressed automatically. New in Tornado 4.0.gzip
: Deprecated alias forcompress_response
since Tornado 4.0.log_function
: This function will be called at the end of every request to log the result (with one argument, theRequestHandler
object). The default implementation writes to thelogging
module’s root logger. May also be customized by overridingApplication.log_request
.serve_traceback
: IfTrue
, the default error page will include the traceback of the error. This option is new in Tornado 3.2; previously this functionality was controlled by thedebug
setting.ui_modules
andui_methods
: May be set to a mapping ofUIModule
or UI methods to be made available to templates. May be set to a module, dictionary, or a list of modules and/or dicts. See UI modules for more details.websocket_ping_interval
: If set to a number, all websockets will be pinged every n seconds. This can help keep the connection alive through certain proxy servers which close idle connections, and it can detect if the websocket has failed without being properly closed.websocket_ping_timeout
: If the ping interval is set, and the server doesn’t receive a ‘pong’ in this many seconds, it will close the websocket. The default is three times the ping interval, with a minimum of 30 seconds. Ignored if the ping interval is not set.
Authentication and security settings:
cookie_secret
: Used byRequestHandler.get_secure_cookie
andset_secure_cookie
to sign cookies.key_version
: Used by requestHandlerset_secure_cookie
to sign cookies with a specific key whencookie_secret
is a key dictionary.login_url
: Theauthenticated
decorator will redirect to this url if the user is not logged in. Can be further customized by overridingRequestHandler.get_login_url
xsrf_cookies
: IfTrue
, Cross-site request forgery protection will be enabled.xsrf_cookie_version
: Controls the version of new XSRF cookies produced by this server. Should generally be left at the default (which will always be the highest supported version), but may be set to a lower value temporarily during version transitions. New in Tornado 3.2.2, which introduced XSRF cookie version 2.xsrf_cookie_kwargs
: May be set to a dictionary of additional arguments to be passed toRequestHandler.set_cookie
for the XSRF cookie.twitter_consumer_key
,twitter_consumer_secret
,friendfeed_consumer_key
,friendfeed_consumer_secret
,google_consumer_key
,google_consumer_secret
,facebook_api_key
,facebook_secret
: Used in thetornado.auth
module to authenticate to various APIs.
Template settings:
autoescape
: Controls automatic escaping for templates. May be set toNone
to disable escaping, or to the name of a function that all output should be passed through. Defaults to"xhtml_escape"
. Can be changed on a per-template basis with the{% autoescape %}
directive.compiled_template_cache
: Default isTrue
; ifFalse
templates will be recompiled on every request. This option is new in Tornado 3.2; previously this functionality was controlled by thedebug
setting.template_path
: Directory containing template files. Can be further customized by overridingRequestHandler.get_template_path
template_loader
: Assign to an instance oftornado.template.BaseLoader
to customize template loading. If this setting is used thetemplate_path
andautoescape
settings are ignored. Can be further customized by overridingRequestHandler.create_template_loader
.template_whitespace
: Controls handling of whitespace in templates; seetornado.template.filter_whitespace
for allowed values. New in Tornado 4.3.
Static file settings:
static_hash_cache
: Default isTrue
; ifFalse
static urls will be recomputed on every request. This option is new in Tornado 3.2; previously this functionality was controlled by thedebug
setting.static_path
: Directory from which static files will be served.static_url_prefix
: Url prefix for static files, defaults to"/static/"
.static_handler_class
,static_handler_args
: May be set to use a different handler for static files instead of the defaulttornado.web.StaticFileHandler
.static_handler_args
, if set, should be a dictionary of keyword arguments to be passed to the handler’sinitialize
method.
-
-
Application.
listen
(port: int, address: str = '', **kwargs) → tornado.httpserver.HTTPServer[source]¶ Starts an HTTP server for this application on the given port.
This is a convenience alias for creating an
HTTPServer
object and calling its listen method. Keyword arguments not supported byHTTPServer.listen
are passed to theHTTPServer
constructor. For advanced uses (e.g. multi-process mode), do not use this method; create anHTTPServer
and call itsTCPServer.bind
/TCPServer.start
methods directly.Note that after calling this method you still need to call
IOLoop.current().start()
to start the server.Returns the
HTTPServer
object.Changed in version 4.3: Now returns the
HTTPServer
object.
-
Application.
add_handlers
(handlers: List[Union[Rule, Tuple]])[source]¶ Appends the given handlers to our handler list.
Host patterns are processed sequentially in the order they were added. All matching patterns will be considered.
-
Application.
get_handler_delegate
(request: tornado.httputil.HTTPServerRequest, target_class: Type[tornado.web.RequestHandler], target_kwargs: Optional[Dict[str, Any]] = None, path_args: Optional[List[bytes]] = None, path_kwargs: Optional[Dict[str, bytes]] = None) → tornado.web._HandlerDelegate[source]¶ Returns
HTTPMessageDelegate
that can serve a request for application andRequestHandler
subclass.Parameters: - request (httputil.HTTPServerRequest) – current HTTP request.
- target_class (RequestHandler) – a
RequestHandler
class. - target_kwargs (dict) – keyword arguments for
target_class
constructor. - path_args (list) – positional arguments for
target_class
HTTP method that will be executed while handling a request (get
,post
or any other). - path_kwargs (dict) – keyword arguments for
target_class
HTTP method.
-
Application.
reverse_url
(name: str, *args) → str[source]¶ Returns a URL path for handler named
name
The handler must be added to the application as a named
URLSpec
.Args will be substituted for capturing groups in the
URLSpec
regex. They will be converted to strings if necessary, encoded as utf8, and url-escaped.
-
Application.
log_request
(handler: tornado.web.RequestHandler) → None[source]¶ Writes a completed HTTP request to the logs.
By default writes to the python root logger. To change this behavior either subclass Application and override this method, or pass a function in the application settings dictionary as
log_function
.
-
class
tornado.web.
URLSpec
(pattern: Union[str, Pattern[AnyStr]], handler: Any, kwargs: Optional[Dict[str, Any]] = None, name: Optional[str] = None)[source]¶ Specifies mappings between URLs and handlers.
Parameters:
pattern
: Regular expression to be matched. Any capturing groups in the regex will be passed in to the handler’s get/post/etc methods as arguments (by keyword if named, by position if unnamed. Named and unnamed capturing groups may not be mixed in the same rule).handler
:RequestHandler
subclass to be invoked.kwargs
(optional): A dictionary of additional arguments to be passed to the handler’s constructor.name
(optional): A name for this handler. Used byreverse_url
.
The
URLSpec
class is also available under the nametornado.web.url
.
Decorators¶
-
tornado.web.
authenticated
(method: Callable[[...], Optional[Awaitable[None]]]) → Callable[[...], Optional[Awaitable[None]]][source]¶ Decorate methods with this to require that the user be logged in.
If the user is not logged in, they will be redirected to the configured
login url
.If you configure a login url with a query parameter, Tornado will assume you know what you’re doing and use it as-is. If not, it will add a
next
parameter so the login page knows where to send you once you’re logged in.
-
tornado.web.
addslash
(method: Callable[[...], Optional[Awaitable[None]]]) → Callable[[...], Optional[Awaitable[None]]][source]¶ Use this decorator to add a missing trailing slash to the request path.
For example, a request to
/foo
would redirect to/foo/
with this decorator. Your request handler mapping should use a regular expression liker'/foo/?'
in conjunction with using the decorator.
-
tornado.web.
removeslash
(method: Callable[[...], Optional[Awaitable[None]]]) → Callable[[...], Optional[Awaitable[None]]][source]¶ Use this decorator to remove trailing slashes from the request path.
For example, a request to
/foo/
would redirect to/foo
with this decorator. Your request handler mapping should use a regular expression liker'/foo/*'
in conjunction with using the decorator.
-
tornado.web.
stream_request_body
(cls: Type[tornado.web.RequestHandler]) → Type[tornado.web.RequestHandler][source]¶ Apply to
RequestHandler
subclasses to enable streaming body support.This decorator implies the following changes:
HTTPServerRequest.body
is undefined, and body arguments will not be included inRequestHandler.get_argument
.RequestHandler.prepare
is called when the request headers have been read instead of after the entire body has been read.- The subclass must define a method
data_received(self, data):
, which will be called zero or more times as data is available. Note that if the request has an empty body,data_received
may not be called. prepare
anddata_received
may return Futures (such as via@gen.coroutine
, in which case the next method will not be called until those futures have completed.- The regular HTTP method (
post
,put
, etc) will be called after the entire body has been read.
See the file receiver demo for example usage.
Everything else¶
-
exception
tornado.web.
HTTPError
(status_code: int = 500, log_message: Optional[str] = None, *args, **kwargs)[source]¶ An exception that will turn into an HTTP error response.
Raising an
HTTPError
is a convenient alternative to callingRequestHandler.send_error
since it automatically ends the current function.To customize the response sent with an
HTTPError
, overrideRequestHandler.write_error
.Parameters: - status_code (int) – HTTP status code. Must be listed in
httplib.responses
unless thereason
keyword argument is given. - log_message (str) – Message to be written to the log for this error
(will not be shown to the user unless the
Application
is in debug mode). May contain%s
-style placeholders, which will be filled in with remaining positional parameters. - reason (str) – Keyword-only argument. The HTTP “reason” phrase
to pass in the status line along with
status_code
. Normally determined automatically fromstatus_code
, but can be used to use a non-standard numeric code.
- status_code (int) – HTTP status code. Must be listed in
-
exception
tornado.web.
Finish
[source]¶ An exception that ends the request without producing an error response.
When
Finish
is raised in aRequestHandler
, the request will end (callingRequestHandler.finish
if it hasn’t already been called), but the error-handling methods (includingRequestHandler.write_error
) will not be called.If
Finish()
was created with no arguments, the pending response will be sent as-is. IfFinish()
was given an argument, that argument will be passed toRequestHandler.finish()
.This can be a more convenient way to implement custom error pages than overriding
write_error
(especially in library code):if self.current_user is None: self.set_status(401) self.set_header('WWW-Authenticate', 'Basic realm="something"') raise Finish()
Changed in version 4.3: Arguments passed to
Finish()
will be passed on toRequestHandler.finish
.
-
exception
tornado.web.
MissingArgumentError
(arg_name: str)[source]¶ Exception raised by
RequestHandler.get_argument
.This is a subclass of
HTTPError
, so if it is uncaught a 400 response code will be used instead of 500 (and a stack trace will not be logged).New in version 3.1.
-
class
tornado.web.
UIModule
(handler: tornado.web.RequestHandler)[source]¶ A re-usable, modular UI unit on a page.
UI modules often execute additional queries, and they can include additional CSS and JavaScript that will be included in the output page, which is automatically inserted on page render.
Subclasses of UIModule must override the
render
method.-
embedded_javascript
() → Optional[str][source]¶ Override to return a JavaScript string to be embedded in the page.
-
javascript_files
() → Optional[Iterable[str]][source]¶ Override to return a list of JavaScript files needed by this module.
If the return values are relative paths, they will be passed to
RequestHandler.static_url
; otherwise they will be used as-is.
-
embedded_css
() → Optional[str][source]¶ Override to return a CSS string that will be embedded in the page.
-
css_files
() → Optional[Iterable[str]][source]¶ Override to returns a list of CSS files required by this module.
If the return values are relative paths, they will be passed to
RequestHandler.static_url
; otherwise they will be used as-is.
-
html_head
() → Optional[str][source]¶ Override to return an HTML string that will be put in the <head/> element.
-
-
class
tornado.web.
ErrorHandler
(application: tornado.web.Application, request: tornado.httputil.HTTPServerRequest, **kwargs)[source]¶ Generates an error response with
status_code
for all requests.
-
class
tornado.web.
FallbackHandler
(application: tornado.web.Application, request: tornado.httputil.HTTPServerRequest, **kwargs)[source]¶ A
RequestHandler
that wraps another HTTP server callback.The fallback is a callable object that accepts an
HTTPServerRequest
, such as anApplication
ortornado.wsgi.WSGIContainer
. This is most useful to use both TornadoRequestHandlers
and WSGI in the same server. Typical usage:wsgi_app = tornado.wsgi.WSGIContainer( django.core.handlers.wsgi.WSGIHandler()) application = tornado.web.Application([ (r"/foo", FooHandler), (r".*", FallbackHandler, dict(fallback=wsgi_app), ])
-
class
tornado.web.
RedirectHandler
(application: tornado.web.Application, request: tornado.httputil.HTTPServerRequest, **kwargs)[source]¶ Redirects the client to the given URL for all GET requests.
You should provide the keyword argument
url
to the handler, e.g.:application = web.Application([ (r"/oldpath", web.RedirectHandler, {"url": "/newpath"}), ])
RedirectHandler
supports regular expression substitutions. E.g., to swap the first and second parts of a path while preserving the remainder:application = web.Application([ (r"/(.*?)/(.*?)/(.*)", web.RedirectHandler, {"url": "/{1}/{0}/{2}"}), ])
The final URL is formatted with
str.format
and the substrings that match the capturing groups. In the above example, a request to “/a/b/c” would be formatted like:str.format("/{1}/{0}/{2}", "a", "b", "c") # -> "/b/a/c"
Use Python’s format string syntax to customize how values are substituted.
Changed in version 4.5: Added support for substitutions into the destination URL.
Changed in version 5.0: If any query arguments are present, they will be copied to the destination URL.
-
class
tornado.web.
StaticFileHandler
(application: tornado.web.Application, request: tornado.httputil.HTTPServerRequest, **kwargs)[source]¶ A simple handler that can serve static content from a directory.
A
StaticFileHandler
is configured automatically if you pass thestatic_path
keyword argument toApplication
. This handler can be customized with thestatic_url_prefix
,static_handler_class
, andstatic_handler_args
settings.To map an additional path to this handler for a static data directory you would add a line to your application like:
application = web.Application([ (r"/content/(.*)", web.StaticFileHandler, {"path": "/var/www"}), ])
The handler constructor requires a
path
argument, which specifies the local root directory of the content to be served.Note that a capture group in the regex is required to parse the value for the
path
argument to the get() method (different than the constructor argument above); seeURLSpec
for details.To serve a file like
index.html
automatically when a directory is requested, setstatic_handler_args=dict(default_filename="index.html")
in your application settings, or adddefault_filename
as an initializer argument for yourStaticFileHandler
.To maximize the effectiveness of browser caching, this class supports versioned urls (by default using the argument
?v=
). If a version is given, we instruct the browser to cache this file indefinitely.make_static_url
(also available asRequestHandler.static_url
) can be used to construct a versioned url.This handler is intended primarily for use in development and light-duty file serving; for heavy traffic it will be more efficient to use a dedicated static file server (such as nginx or Apache). We support the HTTP
Accept-Ranges
mechanism to return partial content (because some browsers require this functionality to be present to seek in HTML5 audio or video).Subclassing notes
This class is designed to be extensible by subclassing, but because of the way static urls are generated with class methods rather than instance methods, the inheritance patterns are somewhat unusual. Be sure to use the
@classmethod
decorator when overriding a class method. Instance methods may use the attributesself.path
self.absolute_path
, andself.modified
.Subclasses should only override methods discussed in this section; overriding other methods is error-prone. Overriding
StaticFileHandler.get
is particularly problematic due to the tight coupling withcompute_etag
and other methods.To change the way static urls are generated (e.g. to match the behavior of another server or CDN), override
make_static_url
,parse_url_path
,get_cache_time
, and/orget_version
.To replace all interaction with the filesystem (e.g. to serve static content from a database), override
get_content
,get_content_size
,get_modified_time
,get_absolute_path
, andvalidate_absolute_path
.Changed in version 3.1: Many of the methods for subclasses were added in Tornado 3.1.
-
compute_etag
() → Optional[str][source]¶ Sets the
Etag
header based on static url version.This allows efficient
If-None-Match
checks against cached versions, and sends the correctEtag
for a partial response (i.e. the sameEtag
as the full file).New in version 3.1.
-
set_headers
() → None[source]¶ Sets the content and caching headers on the response.
New in version 3.1.
-
should_return_304
() → bool[source]¶ Returns True if the headers indicate that we should return 304.
New in version 3.1.
-
classmethod
get_absolute_path
(root: str, path: str) → str[source]¶ Returns the absolute location of
path
relative toroot
.root
is the path configured for thisStaticFileHandler
(in most cases thestatic_path
Application
setting).This class method may be overridden in subclasses. By default it returns a filesystem path, but other strings may be used as long as they are unique and understood by the subclass’s overridden
get_content
.New in version 3.1.
-
validate_absolute_path
(root: str, absolute_path: str) → Optional[str][source]¶ Validate and return the absolute path.
root
is the configured path for theStaticFileHandler
, andpath
is the result ofget_absolute_path
This is an instance method called during request processing, so it may raise
HTTPError
or use methods likeRequestHandler.redirect
(return None after redirecting to halt further processing). This is where 404 errors for missing files are generated.This method may modify the path before returning it, but note that any such modifications will not be understood by
make_static_url
.In instance methods, this method’s result is available as
self.absolute_path
.New in version 3.1.
-
classmethod
get_content
(abspath: str, start: Optional[int] = None, end: Optional[int] = None) → Generator[bytes, None, None][source]¶ Retrieve the content of the requested resource which is located at the given absolute path.
This class method may be overridden by subclasses. Note that its signature is different from other overridable class methods (no
settings
argument); this is deliberate to ensure thatabspath
is able to stand on its own as a cache key.This method should either return a byte string or an iterator of byte strings. The latter is preferred for large files as it helps reduce memory fragmentation.
New in version 3.1.
-
classmethod
get_content_version
(abspath: str) → str[source]¶ Returns a version string for the resource at the given path.
This class method may be overridden by subclasses. The default implementation is a SHA-512 hash of the file’s contents.
New in version 3.1.
-
get_content_size
() → int[source]¶ Retrieve the total size of the resource at the given path.
This method may be overridden by subclasses.
New in version 3.1.
Changed in version 4.0: This method is now always called, instead of only when partial results are requested.
-
get_modified_time
() → Optional[datetime.datetime][source]¶ Returns the time that
self.absolute_path
was last modified.May be overridden in subclasses. Should return a
datetime
object or None.New in version 3.1.
-
get_content_type
() → str[source]¶ Returns the
Content-Type
header to be used for this request.New in version 3.1.
-
get_cache_time
(path: str, modified: Optional[datetime.datetime], mime_type: str) → int[source]¶ Override to customize cache control behavior.
Return a positive number of seconds to make the result cacheable for that amount of time or 0 to mark resource as cacheable for an unspecified amount of time (subject to browser heuristics).
By default returns cache expiry of 10 years for resources requested with
v
argument.
-
classmethod
make_static_url
(settings: Dict[str, Any], path: str, include_version: bool = True) → str[source]¶ Constructs a versioned url for the given path.
This method may be overridden in subclasses (but note that it is a class method rather than an instance method). Subclasses are only required to implement the signature
make_static_url(cls, settings, path)
; other keyword arguments may be passed throughstatic_url
but are not standard.settings
is theApplication.settings
dictionary.path
is the static path being requested. The url returned should be relative to the current host.include_version
determines whether the generated URL should include the query string containing the version hash of the file corresponding to the givenpath
.
-
parse_url_path
(url_path: str) → str[source]¶ Converts a static URL path into a filesystem path.
url_path
is the path component of the URL withstatic_url_prefix
removed. The return value should be filesystem path relative tostatic_path
.This is the inverse of
make_static_url
.
-
classmethod
get_version
(settings: Dict[str, Any], path: str) → Optional[str][source]¶ Generate the version string to be used in static URLs.
settings
is theApplication.settings
dictionary andpath
is the relative location of the requested asset on the filesystem. The returned value should be a string, orNone
if no version could be determined.Changed in version 3.1: This method was previously recommended for subclasses to override;
get_content_version
is now preferred as it allows the base class to handle caching of the result.
-