cyclone.webRequestHandler and Application classes

The cyclone web framework looks a bit like ( or Google’s webapp (, but with additional tools and optimizations to take advantage of the non-blocking web server and tools.

Here is the canonical “Hello, world” example app:

import cyclone.web
from twisted.internet import reactor

class MainHandler(cyclone.web.RequestHandler):
    def get(self):
        self.write("Hello, world")

if __name__ == "__main__":
    application = cyclone.web.Application([
        (r"/", MainHandler),
    reactor.listenTCP(8888, application)

See the cyclone walkthrough on for more details and a good getting started guide.

Thread-safety notes

In general, methods on RequestHandler and elsewhere in cyclone are not thread-safe. In particular, methods such as write(), finish(), and flush() must only be called from the main thread. For more information on using threads, please check the twisted documentation:

Request handlers

class cyclone.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.

If you want lists to be serialized when calling self.write() set serialize_lists to True. This may have some security implications if you are not protecting against XSRF with other means (such as a XSRF token). More details on this vulnerability here:

Entry points


Hook for subclass initialization.

A dictionary passed as the third argument of a url spec will be supplied as keyword arguments to initialize().


class ProfileHandler(RequestHandler):
    def initialize(self, database):
        self.database = database

    def get(self, username):

app = Application([
    (r'/user/(.*)', ProfileHandler, dict(database=database)),

Called at the beginning of a request before get/post/etc.

Override this method to perform common initialization regardless of the request method.


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 to handle the corresponding HTTP method.

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

Called when a request does not match any implemented methods.


class ExampleHandler(RequestHandler):
    def get(self):
        self.write('That was a GET request!')

    def default(self):
        self.write('That was anything but a GET request!')


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


The cyclone.httpserver.HTTPRequest object containing additional request parameters including e.g. headers and body data.


The path_args and path_kwargs attributes contain the positional and keyword arguments that are passed to the get/post/etc methods. These attributes are set before those methods are called, so the values are available during prepare.


RequestHandler.set_status(status_code, reason=None)[source]

Sets the status code for our response.

  • status_code (int) – Response status code. If reason is None, it must be present in httplib.responses.
  • reason (string) – Human-readable reason phrase describing the status code. If None, it will be filled in from httplib.responses.
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.add_header(name, value)[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.


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.


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.


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 anatomy-of-a-subtle-json-vulnerability.aspx


Flushes the current output buffer to the network.


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.


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, permanent=False, status=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=500, **kwargs)[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, **kwargs)[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.

For historical reasons, if a method get_error_html exists, it will be used instead of the default write_error implementation. get_error_html returned a string instead of producing output normally, and had different semantics for exception handling. Users of get_error_html are encouraged to convert their code to override write_error instead.

In order for error pages to be generated for paths that do not match any handlers, you can use the error_handler keyword argument when instantiating the cyclone.web.Application object.

For example:

import cyclone.web
import httplib

class CustomErrorPageMixin(object):
    def write_error(self, status_code, **kwargs):
        kwargs["code"] = status_code
        if 'message' not in kwargs:
            kwargs["message"] = httplib.responses[status_code]

            self.render("error_%d.html" % status_code,
        except IOError:
            self.render("error_all.html", fields=kwargs)

class CustomErrorHandler(CustomErrorPageMixin,

class BaseHandler(CustomErrorPageMixin, cyclone.web.RequestHandler):

Then, when constructing the cyclone.web.Application object:

from cyclone import web
application = web.Application([
    (r"/", MainPageHandler),
], error_handler=CustomErrorHandler)

This technique is also compatible with Bottle-style applications:

from cyclone.bottle import create_app
# create_app takes the same arguments as run
application = create_app(base_handler=BaseHandler,

Resets all headers and content for this response.



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 for available attributes.

Deletes the cookie with the given name.


Deletes all the cookies the user sent with this request.

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

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

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 the max_age_days parameter to get_secure_cookie.

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

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.



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


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 csrf-protection-bypass-in-ruby-on-rails


Computes the etag header to be used for this request.

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


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 application setting. If a template_loader application setting is supplied, uses that instead.


Determines the user’s locale from Accept-Language header.



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


Override to customize the login URL based on the request.

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


Returns the status code for our response.


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.


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 cyclone.locale.Locale object, most likely obtained via a call like cyclone.locale.get(“en”)

RequestHandler.on_connection_close(*args, **kwargs)[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, 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.


An alias for self.application.settings.

RequestHandler.static_url(path, include_host=None)[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.

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 an include_host attribute, that value will be used as the default for all static_url calls that do not pass include_host as a keyword argument.


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 cyclone.web.Application(handlers=None, default_host='', transforms=None, error_handler=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),
reactor.listenTCP(8888, application)

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 (note that a StaticFileHandler 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),

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. A custom subclass of StaticFileHandler can be specified with the static_handler_class setting.

It is also possible to customize the error pages the application generates in case it does not find any handler for the incoming request by using the error_handler keyword argument. This allows for consistent error pages across the application.


Additonal keyword arguments passed to the constructor are saved in the settings dictionary, and are often referred to in documentation as “application 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 Cyclone (although in some cases richer customization is possible by overriding methods in a subclass of RequestHandler). Some applications also like to use the settings dictionary as a way to make application-specific settings available to handlers without using global variables. Settings used in Cyclone are described below.

General settings:

  • debug: If True the application runs in debug mode, described in Debug mode and automatic reloading.
  • xheaders: If True the application uses X-Real-IP and X-Forwarded-For HTTP headers. Use this when your server is reverse proxied by Nginx.
  • gzip: If True, responses in textual formats will be gzipped automatically.
  • log_function: This function will be called at the end of every request to log the result (with one argument, the RequestHandler object). The default implementation writes to the logging module’s root logger. May also be customized by overriding Application.log_request.
  • ui_modules and ui_methods: May be set to a mapping of UIModule 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.

Authentication and security settings:

Template settings:

  • autoescape: Controls automatic escaping for templates. May be set to None 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.
  • template_path: Directory containing template files. Can be further customized by overriding RequestHandler.get_template_path
  • template_loader: Assign to an instance of cyclone.template.BaseLoader to customize template loading. If this setting is used the template_path and autoescape settings are ignored. Can be further customized by overriding RequestHandler.create_template_loader.

Static file settings:

  • 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 default cyclone.web.StaticFileHandler. static_handler_args, if set, should be a dictionary of keyword arguments to be passed to the handler’s initialize method.

alias of HTTPConnection

add_handlers(host_pattern, host_handlers)[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.


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.

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.


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 cyclone.web.URLSpec(pattern, handler_class, kwargs=None, name=None)[source]

Specifies mappings between URLs and handlers.

Creates a URLSpec.


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

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



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 terminate the HTTP request. Without this decorator, the request is automatically finished when the get() or post() method returns.

from twisted.internet import reactor

class MyRequestHandler(web.RequestHandler):
    def get(self):
        self.write("Processing your request...")
        reactor.callLater(5, self.do_something)

    def do_something(self):

It may be used for Comet and similar push techniques.


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


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.


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 cyclone.web.HTTPError(status_code, log_message=None, *args, **kwargs)[source]

An exception that will turn into an HTTP error response.

  • status_code (int) – HTTP status code. Must be listed in httplib.responses unless the reason keyword argument is given.
  • log_message (string) – 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 (string) – Keyword-only argument. The HTTP “reason” phrase to pass in the status line along with status_code. Normally determined automatically from status_code, but can be used to use a non-standard numeric code.
exception cyclone.web.HTTPAuthenticationRequired(log_message=None, auth_type='Basic', realm='Restricted Access', **kwargs)[source]

An exception that will turn into an HTTP 401, Authentication Required.

The arguments are used to compose the WWW-Authenticate header. See for details.

  • auth_type (string) – Authentication type (Basic, Digest, etc)
  • realm (string) – Realm (Usually displayed by the browser)
class cyclone.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.


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


Returns a list of JavaScript files required by this module.


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


Returns a list of CSS files required by this module.


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


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 cyclone.web.ErrorHandler(application, request, **kwargs)[source]

Generates an error response with status_code for all requests.

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

A RequestHandler that wraps another HTTP server callback.

Tornado has this to combine RequestHandlers and WSGI handlers, but it’s not supported in cyclone and is just here for compatibily purposes.

class cyclone.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 cyclone.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. Override get_cache_time method for more fine-grained cache control.


For subclass to add extra headers to the response

get_cache_time(path, modified, mime_type)[source]

Override to customize cache control behavior.

Return a positive number of seconds to trigger aggressive caching or 0 to mark resource as cacheable, only.

By default returns cache expiry of 10 years for resources requested with “v” argument.

classmethod make_static_url(settings, path)[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).

settings is the Application.settings dictionary. path is the static path being requested. The url returned should be relative to the current host.

classmethod get_version(settings, path)[source]

Generate the version string to be used in static URLs.

This method may be overridden in subclasses (but note that it is a class method rather than a static method). The default implementation uses a hash of the file’s contents.

settings is the Application.settings dictionary and path is the relative location of the requested asset on the filesystem. The returned value should be a string, or None if no version could be determined.


Converts a static URL path into a filesystem path.

url_path is the path component of the URL with static_url_prefix removed. The return value should be filesystem path relative to static_path.