Skip to content

octoprint.server.util.tornado#

CorsSupportMixin #

Bases: tornado.web.RequestHandler

tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>_ mixin that makes sure to set CORS headers similarly to the Flask backed API endpoints.

CustomHTTP1Connection(stream, is_client, params = None, context = None) #

Bases: tornado.http1connection.HTTP1Connection

A custom implementation of tornado.http1connection.HTTP1Connection which upon checking the Content-Length of the request against the configured maximum utilizes max_body_sizes and default_max_body_size as a fallback.

CustomHTTP1ConnectionParameters(*args, **kwargs) #

Bases: tornado.http1connection.HTTP1ConnectionParameters

An implementation of tornado.http1connection.HTTP1ConnectionParameters that adds two new parameters max_body_sizes and default_max_body_size.

For a description of these please see the documentation of CustomHTTPServer above.

CustomHTTP1ServerConnection #

Bases: tornado.http1connection.HTTP1ServerConnection

A custom implementation of tornado.http1connection.HTTP1ServerConnection which utilizes a CustomHTTP1Connection instead of a tornado.http1connection.HTTP1Connection in _server_request_loop. The implementation logic is otherwise the same as tornado.http1connection.HTTP1ServerConnection.

CustomHTTPServer(*args, **kwargs) #

Bases: tornado.httpserver.HTTPServer

Custom implementation of tornado.httpserver.HTTPServer that allows defining max body sizes depending on path and method.

The implementation is mostly taken from tornado.httpserver.HTTPServer, the only difference is the creation of a CustomHTTP1ConnectionParameters instance instead of tornado.http1connection.HTTP1ConnectionParameters which is supplied with the two new constructor arguments max_body_sizes and max_default_body_size and the creation of a CustomHTTP1ServerConnection instead of a tornado.http1connection.HTTP1ServerConnection upon connection by a client.

max_body_sizes is expected to be an iterable containing tuples of the form (method, path regex, maximum body size), with method and path regex having to match in order for maximum body size to take affect.

default_max_body_size is the default maximum body size to apply if no specific one from max_body_sizes matches.

DeprecatedEndpointHandler #

Bases: CorsSupportMixin, tornado.web.RequestHandler

tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>_ that redirects to another url and logs a deprecation warning.

Parameters:

  • url (str) –

    URL to which to redirect

LargeResponseHandler #

Bases: RequestlessExceptionLoggingMixin, CorsSupportMixin, tornado.web.StaticFileHandler

Customized tornado.web.StaticFileHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#tornado.web.StaticFileHandler>_ that allows delivery of the requested resource as attachment and access and request path validation through optional callbacks. Note that access validation takes place before path validation.

Parameters:

  • path (str) –

    The system path from which to serve files (this will be forwarded to the initialize method of :class:~tornado.web.StaticFileHandler)

  • default_filename (str) –

    The default filename to serve if none is explicitly specified and the request references a subdirectory of the served path (this will be forwarded to the initialize method of :class:~tornado.web.StaticFileHandler as the default_filename keyword parameter). Defaults to None.

  • as_attachment (bool) –

    Whether to serve requested files with Content-Disposition: attachment header (True) or not. Defaults to False.

  • allow_client_caching (bool) –

    Whether to allow the client to cache (by not setting any Cache-Control or Expires headers on the response) or not.

  • access_validation (function) –

    Callback to call in the get method to validate access to the resource. Will be called with self.request as parameter which contains the full tornado request object. Should raise a tornado.web.HTTPError if access is not allowed in which case the request will not be further processed. Defaults to None and hence no access validation being performed.

  • path_validation (function) –

    Callback to call in the get method to validate the requested path. Will be called with the requested path as parameter. Should raise a tornado.web.HTTPError (e.g. an 404) if the requested path does not pass validation in which case the request will not be further processed. Defaults to None and hence no path validation being performed.

  • etag_generator (function) –

    Callback to call for generating the value of the ETag response header. Will be called with the response handler as parameter. May return None to prevent the ETag response header from being set. If not provided the last modified time of the file in question will be used as returned by get_content_version.

  • name_generator (function) –

    Callback to call for generating the value of the attachment file name header. Will be called with the requested path as parameter.

  • mime_type_guesser (function) –

    Callback to guess the mime type to use for the content type encoding of the response. Will be called with the requested path on disk as parameter.

  • is_pre_compressed (bool) –

    if the file is expected to be pre-compressed, i.e, if there is a file in the same directory with the same name, but with '.gz' appended and gzip-encoded

original_absolute_path property #

The path of the uncompressed file corresponding to the compressed file

streamed_get(path, include_body = True) #

Version of StaticFileHandler.get that doesn't support ranges or ETag but streams the content. Helpful for files that might still change while being transmitted (e.g. log files)

StaticDataHandler #

Bases: RequestlessExceptionLoggingMixin, CorsSupportMixin, tornado.web.RequestHandler

tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>_ that returns static data of a configured content_type.

Parameters:

  • data (str) –

    The data with which to respond

  • content_type (str) –

    The content type with which to respond. Defaults to text/plain

UploadStorageFallbackHandler #

Bases: RequestlessExceptionLoggingMixin, CorsSupportMixin

A RequestHandler similar to tornado.web.FallbackHandler which fetches any files contained in the request bodies of content type multipart, stores them in temporary files and supplies the fallback with the file's name, content_type, path and size instead via a rewritten body.

Basically similar to what the nginx upload module does.

Basic request body example:

.. code-block:: none

------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file"; filename="test.gcode"
Content-Type: application/octet-stream

...
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="apikey"

my_funny_apikey
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="select"

true
------WebKitFormBoundarypYiSUx63abAmhT5C--

That would get turned into:

.. code-block:: none

------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="apikey"

my_funny_apikey
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="select"

true
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.path"
Content-Type: text/plain; charset=utf-8

/tmp/tmpzupkro
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.name"
Content-Type: text/plain; charset=utf-8

test.gcode
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.content_type"
Content-Type: text/plain; charset=utf-8

application/octet-stream
------WebKitFormBoundarypYiSUx63abAmhT5C
Content-Disposition: form-data; name="file.size"
Content-Type: text/plain; charset=utf-8

349182
------WebKitFormBoundarypYiSUx63abAmhT5C--

The underlying application can then access the contained files via their respective paths and just move them where necessary.

BODY_METHODS = ('POST', 'PATCH', 'PUT') class-attribute instance-attribute #

The request methods that may contain a request body.

data_received(chunk) #

Called by Tornado on receiving a chunk of the request body. If request is a multipart request, takes care of processing the multipart data structure via :func:_process_multipart_data. If not, just adds the chunk to internal in-memory buffer.

:param chunk: chunk of data received from Tornado

is_multipart() #

Checks whether this request is a multipart request

prepare() #

Prepares the processing of the request. If it's a request that may contain a request body (as defined in :attr:UploadStorageFallbackHandler.BODY_METHODS) prepares the multipart parsing if content type fits. If it's a body-less request, just calls the fallback with an empty body and finishes the request.

UrlProxyHandler #

Bases: RequestlessExceptionLoggingMixin, CorsSupportMixin, tornado.web.RequestHandler

tornado.web.RequestHandler <http://tornado.readthedocs.org/en/branch4.0/web.html#request-handlers>_ that proxies requests to a preconfigured url and returns the response. Allows delivery of the requested content as attachment and access validation through an optional callback.

This will use tornado.httpclient.AsyncHTTPClient <http://tornado.readthedocs.org/en/branch4.0/httpclient.html#tornado.httpclient.AsyncHTTPClient>_ for making the request to the configured endpoint and return the body of the client response with the status code

from the client response and the following headers
  • Date, Cache-Control, Expires, ETag, Server, Content-Type and Location will be copied over.
  • If as_attachment is set to True, Content-Disposition will be set to attachment. If basename is set including the attachment's filename attribute will be set to the base name followed by the extension guessed based on the MIME type from the Content-Type header of the response. If no extension can be guessed no filename attribute will be set.

Parameters:

  • url (str) –

    URL to forward any requests to. A 404 response will be returned if this is not set. Defaults to None.

  • as_attachment (bool) –

    Whether to serve files with Content-Disposition: attachment header (True) or not. Defaults to False.

  • basename (str) –

    base name of file names to return as part of the attachment header, see above. Defaults to None.

  • access_validation (function) –

    Callback to call in the get method to validate access to the resource. Will be called with self.request as parameter which contains the full tornado request object. Should raise a tornado.web.HTTPError if access is not allowed in which case the request will not be further processed. Defaults to None and hence no access validation being performed.

WsgiInputContainer(wsgi_application, headers = None, forced_headers = None, removed_headers = None) #

A WSGI container for use with Tornado that allows supplying the request body to be used for wsgi.input in the generated WSGI environment upon call.

A RequestHandler can thus provide the WSGI application with a stream for the request body, or a modified body.

Example usage:

.. code-block:: python

wsgi_app = octoprint.server.util.WsgiInputContainer(octoprint_app) application = tornado.web.Application([ (r".*", UploadStorageFallbackHandler, dict(fallback=wsgi_app), ])

The implementation logic is basically the same as tornado.wsgi.WSGIContainer but the __call__ and environ methods have been adjusted to allow for an optionally supplied body argument which is then used for wsgi.input.

__call__(request, body = None) #

Wraps the call against the WSGI app, deriving the WSGI environment from the supplied Tornado HTTPServerRequest.

:param request: the tornado.httpserver.HTTPServerRequest to derive the WSGI environment from :param body: an optional body to use as wsgi.input instead of request.body, can be a string or a stream

environ(request, body = None) staticmethod #

Converts a tornado.httputil.HTTPServerRequest to a WSGI environment.

An optional body to be used for populating wsgi.input can be supplied (either a string or a stream). If not supplied, request.body will be wrapped into a io.BytesIO stream and used instead.

:param request: the tornado.httpserver.HTTPServerRequest to derive the WSGI environment from :param body: an optional body to use as wsgi.input instead of request.body, can be a string or a stream

access_validation_factory(app, validator, *args) #

Creates an access validation wrapper using the supplied validator.

:param validator: the access validator to use inside the validation wrapper :return: an access validator taking a request as parameter and performing the request validation

enable_per_message_deflate_extension() #

This configures tornado.websocket.WebSocketHandler.get_compression_options to support the permessage-deflate extension to the websocket protocol, minimizing data bandwidth if clients support the extension as well

fix_json_encode() #

This makes tornado.escape.json_encode use octoprint.util.JsonEncoding.encode as fallback in order to allow serialization of globally registered types like frozendict and others.

fix_websocket_check_origin() #

This fixes tornado.websocket.WebSocketHandler.check_origin to do the same origin check against the Host header case-insensitively, as defined in RFC6454, Section 4, item 5.

path_validation_factory(path_filter, status_code = 404) #

Creates a request path validation wrapper returning the defined status code if the supplied path_filter returns False.

:param path_filter: the path filter to use on the requested path, should return False for requests that should be responded with the provided error code. :return: a request path validator taking a request path as parameter and performing the request validation