WebSocketHandler

class supriya.tools.webguitools.WebSocketHandler(application, request, **kwargs)[source]

Lineage

digraph InheritanceGraph { graph [background=transparent, bgcolor=transparent, color=lightslategrey, fontname=Arial, outputorder=edgesfirst, overlap=prism, penwidth=2, rankdir=LR, root="__builtin__.object", splines=spline, style="dotted, rounded", truecolor=true]; node [colorscheme=pastel19, fontname=Arial, fontsize=12, penwidth=2, style="filled, rounded"]; edge [color=lightsteelblue2, penwidth=2]; subgraph cluster_builtins { graph [label=builtins]; "builtins.object" [color=1, group=0, label=object, shape=box]; } subgraph cluster_webguitools { graph [label=webguitools]; "supriya.tools.webguitools.WebSocketHandler.WebSocketHandler" [color=black, fontcolor=white, group=2, label=<<B>WebSocketHandler</B>>, shape=box, style="filled, rounded"]; } subgraph cluster_tornado { graph [label=tornado]; "tornado.web.RequestHandler" [color=2, group=1, label=RequestHandler, shape=box]; "tornado.websocket.WebSocketHandler" [color=2, group=1, label=WebSocketHandler, shape=box]; "tornado.web.RequestHandler" -> "tornado.websocket.WebSocketHandler"; } "builtins.object" -> "tornado.web.RequestHandler"; "tornado.websocket.WebSocketHandler" -> "supriya.tools.webguitools.WebSocketHandler.WebSocketHandler"; }

Bases

  • tornado.websocket.WebSocketHandler
  • tornado.web.RequestHandler
  • builtins.object

Attribute summary

add_header(name, value) Adds the given response header and value.
check_etag_header() Checks the Etag header against requests’s If-None-Match.
check_origin(origin) Override to enable support for allowing alternate origins.
check_xsrf_cookie() Verifies that the _xsrf cookie matches the _xsrf argument.
clear() Resets all headers and content for this response.
clear_all_cookies([path, domain]) Deletes all the cookies the user sent with this request.
clear_cookie(name[, path, domain]) Deletes the cookie with the given name.
clear_header(name) Clears an outgoing header, undoing a previous set_header call.
close([code, reason]) Closes this Web Socket.
compute_etag() Computes the etag header to be used for this request.
cookies An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.
create_signed_value(name, value[, version]) Signs and timestamps a string so it cannot be forged.
create_template_loader(template_path) Returns a new template loader for the given path.
current_user The authenticated user for this request.
data_received(chunk) Implement this method to handle streamed request data.
decode_argument(value[, name]) Decodes an argument from the request.
delete(*args, **kwargs)
finish(*args, **kwargs)
flush(*args, **kwargs)
get(*args, **kwargs)
get_argument(name[, default, strip]) Returns the value of the argument with the given name.
get_arguments(name[, strip]) Returns a list of the arguments with the given name.
get_body_argument(name[, default, strip]) Returns the value of the argument with the given name from the request body.
get_body_arguments(name[, strip]) Returns a list of the body arguments with the given name.
get_browser_locale([default]) Determines the user’s locale from Accept-Language header.
get_compression_options()
get_cookie(name[, default]) Gets the value of the cookie with the given name, else default.
get_current_user() Override to determine the current user from, e.g., a cookie.
get_login_url() Override to customize the login URL based on the request.
get_query_argument(name[, default, strip]) Returns the value of the argument with the given name from the request query string.
get_query_arguments(name[, strip]) Returns a list of the query arguments with the given name.
get_secure_cookie(name[, value, ...]) Returns the given signed cookie if it validates, or None.
get_secure_cookie_key_version(name[, value]) Returns the signing key version of the secure cookie.
get_status() Returns the status code for our response.
get_template_namespace() Returns a dictionary to be used as the default template namespace.
get_template_path() Override to customize template path for each handler.
get_user_locale() Override to determine the locale from the authenticated user.
get_websocket_protocol()
head(*args, **kwargs)
initialize() Hook for subclass initialization.
locale The locale for the current session.
log_exception(typ, value, tb) Override to customize logging of uncaught exceptions.
on_close()
on_connection_close()
on_finish() Called after the end of a request.
on_message(message)
on_pong(data) Invoked when the response to a ping frame is received.
open()
options(*args, **kwargs)
patch(*args, **kwargs)
ping(data) Send ping frame to the remote end.
post(*args, **kwargs)
prepare() Called at the beginning of a request before get/post/etc.
put(*args, **kwargs)
redirect(*args, **kwargs)
render(template_name, **kwargs) Renders the template with the given arguments as the response.
render_string(template_name, **kwargs) Generate the given template with the given arguments.
require_setting(name[, feature]) Raises an exception if the given app setting is not defined.
reverse_url(name, *args) Alias for Application.reverse_url.
select_subprotocol(subprotocols) Invoked when a new WebSocket requests specific subprotocols.
send_error(*args, **kwargs)
set_cookie(*args, **kwargs)
set_default_headers() Override this to set HTTP headers at the beginning of the request.
set_etag_header() Sets the response’s Etag header using self.compute_etag().
set_header(*args, **kwargs)
set_nodelay(value) Set the no-delay flag for this stream.
set_secure_cookie(name, value[, ...]) Signs and timestamps a cookie so it cannot be forged.
set_status(*args, **kwargs)
settings An alias for self.application.settings <Application.settings>.
static_url(path[, include_host]) Returns a static URL for the given relative static file path.
update(topic, event)
write(*args, **kwargs)
write_error(status_code, **kwargs) Override to implement custom error pages.
write_message(message[, binary]) Sends the given message to the client of this Web Socket.
xsrf_form_html() An HTML <input/> element to be included with all POST forms.
xsrf_token The XSRF-prevention token for the current user/session.

Read-only properties

(RequestHandler).cookies

An alias for self.request.cookies <.httputil.HTTPServerRequest.cookies>.

(RequestHandler).settings

An alias for self.application.settings <Application.settings>.

(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

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 to set_cookie). For example, xsrf_cookie_kwargs=dict(httponly=True, secure=True) will set the secure and httponly flags on the _xsrf cookie.

Read/write properties

(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 time self.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 while get_current_user() may not, so the latter form is necessary if loading the user requires asynchronous operations.

The user object may any type of the application’s choosing.

(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, or get_browser_locale, which uses the Accept-Language header.

Methods

(RequestHandler).add_header(name, value)

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

Checks the Etag header against requests’s If-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 for If-None-Match before completing the request. The Etag header should be set (perhaps with set_etag_header) before calling this method.

(WebSocketHandler).check_origin(origin)[source]

Override to enable support for allowing alternate origins.

The origin argument is the value of the Origin HTTP header, the url responsible for initiating this request. This method is not called for clients that do not send this header; such requests are always allowed (because all browsers that implement WebSockets support this header, and non-browser clients do not have the same cross-site security concerns).

Should return True to accept the request or False to reject it. By default, rejects all requests with an origin on a host other than this one.

This is a security protection against cross site scripting attacks on browsers, since WebSockets are allowed to bypass the usual same-origin policies and don’t use CORS headers.

To accept all cross-origin traffic (which was the default prior to Tornado 4.0), simply override this method to always return true:

def check_origin(self, origin):
    return True

To allow connections from any subdomain of your site, you might do something like:

def check_origin(self, origin):
    parsed_origin = urllib.parse.urlparse(origin)
    return parsed_origin.netloc.endswith(".mydomain.com")

New in version 4.0.

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

Changed in version 3.2.2: Added support for cookie version 2. Both versions 1 and 2 are supported.

(RequestHandler).clear()

Resets all headers and content for this response.

(RequestHandler).clear_all_cookies(path='/', domain=None)

Deletes all the cookies the user sent with this request.

See clear_cookie for more information on the path and domain parameters.

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

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

(RequestHandler).clear_header(name)

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.

(WebSocketHandler).close(code=None, reason=None)[source]

Closes this Web Socket.

Once the close handshake is successful the socket will be closed.

code may be a numeric status code, taken from the values defined in RFC 6455 section 7.4.1. reason may be a textual message about why the connection is closing. These values are made available to the client, but are not otherwise interpreted by the websocket protocol.

Changed in version 4.0: Added the code and reason arguments.

(RequestHandler).compute_etag()

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_signed_value(name, value, version=None)

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.

(RequestHandler).create_template_loader(template_path)

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

(RequestHandler).data_received(chunk)

Implement this method to handle streamed request data.

Requires the .stream_request_body decorator.

(RequestHandler).decode_argument(value, name=None)

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).delete(*args, **kwargs)
(WebSocketHandler).finish(*args, **kwargs)
(WebSocketHandler).flush(*args, **kwargs)
(WebSocketHandler).get(*args, **kwargs)[source]
(RequestHandler).get_argument(name, default=<object object>, strip=True)

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 url more than once, we return the last value.

The returned value is always unicode.

(RequestHandler).get_arguments(name, strip=True)

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).get_body_argument(name, default=<object object>, strip=True)

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.

The returned value is always unicode.

New in version 3.2.

(RequestHandler).get_body_arguments(name, strip=True)

Returns a list of the body arguments with the given name.

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

The returned values are always unicode.

New in version 3.2.

(RequestHandler).get_browser_locale(default='en_US')

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

See http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4

WebSocketHandler.get_compression_options()[source]

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

(RequestHandler).get_current_user()

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

This method may not be a coroutine.

(RequestHandler).get_login_url()

Override to customize the login URL based on the request.

By default, we use the login_url application setting.

(RequestHandler).get_query_argument(name, default=<object object>, strip=True)

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.

The returned value is always unicode.

New in version 3.2.

(RequestHandler).get_query_arguments(name, strip=True)

Returns a list of the query arguments with the given name.

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

The returned values are always unicode.

New in version 3.2.

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

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

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.

(RequestHandler).get_status()

Returns the status code for our response.

(RequestHandler).get_template_namespace()

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

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

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

(WebSocketHandler).get_websocket_protocol()[source]
(RequestHandler).head(*args, **kwargs)
(RequestHandler).initialize()

Hook for subclass initialization. Called for each request.

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).log_exception(typ, value, tb)

Override to customize logging of uncaught exceptions.

By default logs instances of HTTPError as warnings without stack traces (on the tornado.general logger), and all other exceptions as errors with stack traces (on the tornado.application logger).

New in version 3.1.

WebSocketHandler.on_close()[source]
(WebSocketHandler).on_connection_close()[source]
(RequestHandler).on_finish()

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.

WebSocketHandler.on_message(message)[source]
(WebSocketHandler).on_pong(data)[source]

Invoked when the response to a ping frame is received.

WebSocketHandler.open()[source]
(RequestHandler).options(*args, **kwargs)
(RequestHandler).patch(*args, **kwargs)
(WebSocketHandler).ping(data)[source]

Send ping frame to the remote end.

(RequestHandler).post(*args, **kwargs)
(RequestHandler).prepare()

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: Decorate this method with .gen.coroutine or .return_future to make it asynchronous (the asynchronous decorator cannot be used on prepare). If this method returns a .Future execution will not proceed until the .Future is done.

New in version 3.1: Asynchronous support.

(RequestHandler).put(*args, **kwargs)
(WebSocketHandler).redirect(*args, **kwargs)
(RequestHandler).render(template_name, **kwargs)

Renders the template with the given arguments as the response.

(RequestHandler).render_string(template_name, **kwargs)

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).require_setting(name, feature='this feature')

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

(RequestHandler).reverse_url(name, *args)

Alias for Application.reverse_url.

(WebSocketHandler).select_subprotocol(subprotocols)[source]

Invoked when a new WebSocket requests specific subprotocols.

subprotocols is a list of strings identifying the subprotocols proposed by the client. This method may be overridden to return one of those strings to select it, or None to not select a subprotocol. Failure to select a subprotocol does not automatically abort the connection, although clients may close the connection if none of their proposed subprotocols was selected.

(WebSocketHandler).send_error(*args, **kwargs)[source]
(RequestHandler).set_default_headers()

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

Sets the response’s Etag header using self.compute_etag().

Note: no header will be set if compute_etag() returns None.

This method is called automatically when the request is finished.

(WebSocketHandler).set_header(*args, **kwargs)
(WebSocketHandler).set_nodelay(value)[source]

Set the no-delay flag for this stream.

By default, small messages may be delayed and/or combined to minimize the number of packets sent. This can sometimes cause 200-500ms delays due to the interaction between Nagle’s algorithm and TCP delayed ACKs. To reduce this delay (at the expense of possibly increasing bandwidth usage), call self.set_nodelay(True) once the websocket connection is established.

See .BaseIOStream.set_nodelay for additional details.

New in version 3.1.

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)

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

(WebSocketHandler).set_status(*args, **kwargs)
(RequestHandler).static_url(path, include_host=None, **kwargs)

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 passing include_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 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.

WebSocketHandler.update(topic, event)[source]
(WebSocketHandler).write(*args, **kwargs)
(RequestHandler).write_error(status_code, **kwargs)

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.

(WebSocketHandler).write_message(message, binary=False)[source]

Sends the given message to the client of this Web Socket.

The message may be either a string or a dict (which will be encoded as json). If the binary argument is false, the message will be sent as utf8; in binary mode any byte string is allowed.

If the connection is already closed, raises WebSocketClosedError.

Changed in version 3.2: WebSocketClosedError was added (previously a closed connection would raise an AttributeError)

Changed in version 4.3: Returns a .Future which can be used for flow control.

(RequestHandler).xsrf_form_html()

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.

In a template, this method should be called with {% module xsrf_form_html() %}

See check_xsrf_cookie() above for more information.