tornado.webRequestHandler and Application classes

The Tornado web framework looks a bit like web.py (http://webpy.org/) or Google’s webapp (http://code.google.com/appengine/docs/python/tools/webapp/), but with additional tools and optimizations to take advantage of the Tornado non-blocking web server and tools.

Here is the canonical “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.instance().start()

See the Tornado walkthrough on http://tornadoweb.org for more details and a good getting started guide.

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.

Request handlers

class tornado.web.RequestHandler(application, request, **kwargs)[source]

Subclass this class and define get() or post() to make a handler.

If you want to support more methods than the standard GET/HEAD/POST, you should override the class variable SUPPORTED_METHODS in your RequestHandler class.

Entry points

RequestHandler.initialize()[source]

Hook for subclass initialization.

A dictionary passed as the third argument of a url spec 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()[source]

Called before the actual handler method.

Useful to override in a handler if you want a common bottleneck for all of your requests.

Implement any of the following methods to handle the corresponding HTTP method.

RequestHandler.get(*args, **kwargs)[source]
RequestHandler.post(*args, **kwargs)[source]
RequestHandler.put(*args, **kwargs)[source]
RequestHandler.delete(*args, **kwargs)[source]
RequestHandler.head(*args, **kwargs)[source]
RequestHandler.options(*args, **kwargs)[source]

Input

RequestHandler.get_argument(name, default=, []strip=True)[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 throw an HTTP 400 exception if it is missing.

If the argument appears in the url more than once, we return the last value.

The returned value is always unicode.

RequestHandler.get_arguments(name, strip=True)[source]

Returns a list of the arguments with the given name.

If the argument is not present, returns an empty list.

The returned values are always unicode.

RequestHandler.decode_argument(value, name=None)[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.httpserver.HTTPRequest object containing additional request parameters including e.g. headers and body data.

Output

RequestHandler.set_status(status_code)[source]

Sets the status code for our response.

RequestHandler.set_header(name, value)[source]

Sets the given response header name and value.

If a datetime is given, we automatically format it according to the HTTP specification. If the value is not a string, we convert it to a string. All header values are then encoded as UTF-8.

RequestHandler.write(chunk)[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/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx

RequestHandler.flush(include_footers=False)[source]

Flushes the current output buffer to the network.

RequestHandler.finish(chunk=None)[source]

Finishes this response, ending the HTTP request.

RequestHandler.render(template_name, **kwargs)[source]

Renders the template with the given arguments as the response.

RequestHandler.render_string(template_name, **kwargs)[source]

Generate the given template with the given arguments.

We return the generated string. To generate and write a template as a response, use render() above.

RequestHandler.redirect(url, permanent=False)[source]

Sends a redirect to the given (optionally relative) URL.

RequestHandler.send_error(status_code=500, **kwargs)[source]

Sends the given HTTP error code to the browser.

We also send the error HTML for the given error code as returned by get_error_html. Override that method if you want custom error pages for your application.

RequestHandler.get_error_html(status_code, **kwargs)[source]

Override to implement custom error pages.

get_error_html() should return a string containing the error page, and should not produce output via self.write(). If you use a Tornado template for the error page, you must use “return self.render_string(...)” instead of “self.render()”.

If this error was caused by an uncaught exception, the exception object can be found in kwargs e.g. kwargs[‘exception’]

RequestHandler.clear()[source]

Resets all headers and content for this response.

Cookies

RequestHandler.cookies[source]

A dictionary of Cookie.Morsel objects.

Gets the value of the cookie with the given name, else default.

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

Additional keyword arguments are set on the Cookie.Morsel directly. See http://docs.python.org/library/cookie.html#morsel-objects for available attributes.

Deletes the cookie with the given name.

RequestHandler.clear_all_cookies()[source]

Deletes all the cookies the user sent with this request.

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

In older versions of Tornado (0.1 and 0.2), we did not include the name of the cookie in the cookie signature. To read these old-style cookies, pass include_name=False to this method. Otherwise, all attempts to read old-style cookies will fail (and you may log all your users out whose cookies were written with a previous Tornado version).

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().

RequestHandler.create_signed_value(name, value)[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.

Other

RequestHandler.application

The Application object serving this request

RequestHandler.async_callback(callback, *args, **kwargs)[source]

Obsolete - catches exceptions from the wrapped function.

This function is unnecessary since Tornado 1.1.

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 all POST 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 named X-XSRFToken or X-CSRFToken (the latter is accepted for compatibility with Django).

See http://en.wikipedia.org/wiki/Cross-site_request_forgery

Prior to release 1.1.1, this check was ignored if the HTTP header “X-Requested-With: XMLHTTPRequest” was present. This exception has been shown to be insecure and has been removed. For more information please see http://www.djangoproject.com/weblog/2011/feb/08/security/ http://weblog.rubyonrails.org/2011/2/8/csrf-protection-bypass-in-ruby-on-rails

RequestHandler.compute_etag()[source]

Computes the etag header to be used for this request.

May be overridden to provide custom etag implementations, or may return None to disable tornado’s default etag support.

RequestHandler.get_browser_locale(default='en_US')[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()[source]

Override to determine the current user from, e.g., a cookie.

RequestHandler.get_login_url()[source]

Override to customize the login URL based on the request.

By default, we use the ‘login_url’ application setting.

RequestHandler.get_status()[source]

Returns the status code for our response.

RequestHandler.get_template_path()[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()[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 like tornado.locale.get(“en”)

RequestHandler.on_connection_close()[source]

Called in async handlers if the client closed the connection.

You may override this to clean up resources associated with long-lived connections.

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, feature='this feature')[source]

Raises an exception if the given app setting is not defined.

RequestHandler.reverse_url(name, *args)[source]

Alias for Application.reverse_url.

RequestHandler.settings[source]

An alias for self.application.settings.

RequestHandler.static_url(path)[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).

We append ?v=<signature> to the returned URL, which makes our static file handler set an infinite expiration header on the returned content. The signature is based on the content of the file.

If this handler has a “include_host” attribute, we include the full host for every static URL, including the “http://”. Set this attribute for handlers whose output needs non-relative static path names.

RequestHandler.xsrf_form_html()[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 the ‘xsrf_cookies’ application setting, you must include this HTML within all of your HTML forms.

See check_xsrf_cookie() above for more information.

Application configuration

class tornado.web.Application(handlers=None, default_host='', transforms=None, wsgi=False, **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.instance().start()

The constructor for this class takes in a list of URLSpec objects or (regexp, request_class) tuples. 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.

Each tuple can contain an optional third element, which should be a dictionary if it is present. That dictionary is passed as keyword arguments to the contructor of the handler. This pattern is used for the StaticFileHandler 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),
])

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 the static_url_prefix setting), and we will serve /favicon.ico and /robots.txt from the same directory.

settings

Additonal keyword arguments passed to the constructor are saved in the settings dictionary, and are often referred to in documentation as “application settings”.

listen(port, address='', **kwargs)[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 by HTTPServer.listen are passed to the HTTPServer constructor. For advanced uses (e.g. preforking), do not use this method; create an HTTPServer and call its bind/start methods directly.

Note that after calling this method you still need to call IOLoop.instance().start() to start the server.

add_handlers(host_pattern, host_handlers)[source]

Appends the given handlers to our handler list.

Note that host patterns are processed sequentially in the order they were added, and only the first matching pattern is used. This means that all handlers for a given host must be added in a single add_handlers call.

add_transform(transform_class)[source]

Adds the given OutputTransform to our transform list.

reverse_url(name, *args)[source]

Returns a URL path for handler named name

The handler must be added to the application as a named URLSpec

log_request(handler)[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, handler_class, kwargs={}, name=None)[source]

Specifies mappings between URLs and handlers.

Creates a URLSpec.

Parameters:

pattern: Regular expression to be matched. Any groups in the regex
will be passed in to the handler’s get/post/etc methods as arguments.

handler_class: 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 by
Application.reverse_url.

The URLSpec class is also available under the name tornado.web.url.

Decorators

tornado.web.asynchronous(method)[source]

Wrap request handler methods with this if they are asynchronous.

If this decorator is given, the response is not finished when the method returns. It is up to the request handler to call self.finish() to finish the HTTP request. Without this decorator, the request is automatically finished when the get() or post() method returns.

class MyRequestHandler(web.RequestHandler):
    @web.asynchronous
    def get(self):
       http = httpclient.AsyncHTTPClient()
       http.fetch("http://friendfeed.com/", self._on_download)

    def _on_download(self, response):
       self.write("Downloaded!")
       self.finish()
tornado.web.authenticated(method)[source]

Decorate methods with this to require that the user be logged in.

tornado.web.addslash(method)[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 like r’/foo/?’ in conjunction with using the decorator.

tornado.web.removeslash(method)[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 like r'/foo/*' in conjunction with using the decorator.

Everything else

exception tornado.web.HTTPError(status_code, log_message=None, *args)[source]

An exception that will turn into an HTTP error response.

class tornado.web.UIModule(handler)[source]

A UI re-usable, modular 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.

render(*args, **kwargs)[source]

Overridden in subclasses to return this module’s output.

embedded_javascript()[source]

Returns a JavaScript string that will be embedded in the page.

javascript_files()[source]

Returns a list of JavaScript files required by this module.

embedded_css()[source]

Returns a CSS string that will be embedded in the page.

css_files()[source]

Returns a list of CSS files required by this module.

html_head()[source]

Returns a CSS string that will be put in the <head/> element

html_body()[source]

Returns an HTML string that will be put in the <body/> element

render_string(path, **kwargs)[source]

Renders a template and returns it as a string.

class tornado.web.ErrorHandler(application, request, **kwargs)[source]

Generates an error response with status_code for all requests.

class tornado.web.FallbackHandler(application, request, **kwargs)[source]

A RequestHandler that wraps another HTTP server callback.

The fallback is a callable object that accepts an HTTPRequest, such as an Application or tornado.wsgi.WSGIContainer. This is most useful to use both tornado RequestHandlers 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, request, **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"}),
])
class tornado.web.StaticFileHandler(application, request, **kwargs)[source]

A simple handler that can serve static content from a directory.

To map a path to this handler for a static data directory /var/www, you would add a line to your application like:

application = web.Application([
    (r"/static/(.*)", web.StaticFileHandler, {"path": "/var/www"}),
])

The local root directory of the content should be passed as the “path” argument to the handler.

To support aggressive browser caching, if the argument “v” is given with the path, we set an infinite HTTP expiration header. So, if you want browsers to cache a file indefinitely, send them to, e.g., /static/images/myimage.png?v=xxx.

set_extra_headers(path)[source]

For subclass to add extra headers to the response