octoprint.server

octoprint.server.util

octoprint.server.util.apiKeyRequestHandler(*args, **kwargs)

before_request handler for blueprints which makes sure an API key is provided

octoprint.server.util.corsRequestHandler()

before_request handler for blueprints which sets CORS headers for OPTIONS requests if enabled

octoprint.server.util.corsResponseHandler(resp)

after_request handler for blueprints for which CORS is supported.

Sets Access-Control-Allow-Origin headers for Origin request header on response.

octoprint.server.util.enforceApiKeyRequestHandler()

before_request handler for blueprints which makes sure an API key is provided

octoprint.server.util.loginFromApiKeyRequestHandler()

before_request handler for blueprints which creates a login session for the provided api key (if available)

UI_API_KEY and app session keys are handled as anonymous keys here and ignored.

octoprint.server.util.noCachingExceptGetResponseHandler(resp)

after_request handler for blueprints which shall set no caching headers on their responses to any requests that are not sent with method GET.

See noCachingResponseHandler().

octoprint.server.util.noCachingResponseHandler(resp)

after_request handler for blueprints which shall set no caching headers on their responses.

Sets Cache-Control, Pragma and Expires headers accordingly to prevent all client side caching from taking place.

octoprint.server.util.optionsAllowOrigin(request)

Shortcut for request handling for CORS OPTIONS requests to set CORS headers.

octoprint.server.util.flask

class octoprint.server.util.flask.LessSimpleCache(threshold=500, default_timeout=300)

Slightly improved version of SimpleCache.

Setting default_timeout or timeout to -1 will have no timeout be applied at all.

octoprint.server.util.flask.admin_validator(request)

Validates that the given request is made by an admin user, identified either by API key or existing Flask session.

Must be executed in an existing Flask request context!

Parameters:request – The Flask request object
octoprint.server.util.flask.firstrun_only_access(func)

If you decorate a view with this, it will ensure that first setup has _not_ been done for OctoPrint’s Access Control. Otherwise it will cause a HTTP 403 status code to be returned by the decorated resource.

octoprint.server.util.flask.redirect_to_tornado(request, target, code=302)

Redirects from flask to tornado, flask request context must exist.

Parameters:
  • request
  • target
  • code
Returns:

octoprint.server.util.flask.restricted_access(func)

If you decorate a view with this, it will ensure that first setup has been done for OctoPrint’s Access Control plus that any conditions of the login_required decorator are met (possibly through a session already created by octoprint.server.util.apiKeyRequestHandler earlier in the request processing).

If OctoPrint’s Access Control has not been setup yet (indicated by the “firstRun” flag from the settings being set to True and the userManager not indicating that it’s user database has been customized from default), the decorator will cause a HTTP 403 status code to be returned by the decorated resource.

octoprint.server.util.flask.user_validator(request)

Validates that the given request is made by an authenticated user, identified either by API key or existing Flask session.

Must be executed in an existing Flask request context!

Parameters:request – The Flask request object

octoprint.server.util.sockjs

octoprint.server.util.tornado

class octoprint.server.util.tornado.CustomHTTP1Connection(stream, is_client, params=None, context=None)

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.

class octoprint.server.util.tornado.CustomHTTP1ConnectionParameters(*args, **kwargs)

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.

class octoprint.server.util.tornado.CustomHTTP1ServerConnection(stream, params=None, context=None)

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.

class octoprint.server.util.tornado.CustomHTTPServer(request_callback, no_keep_alive=False, io_loop=None, xheaders=False, ssl_options=None, protocol=None, decompress_request=False, chunk_size=None, max_header_size=None, idle_connection_timeout=None, body_timeout=None, max_body_sizes=None, default_max_body_size=None, max_buffer_size=None)

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.

class octoprint.server.util.tornado.LargeResponseHandler(application, request, **kwargs)

Customized 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.
class octoprint.server.util.tornado.UploadStorageFallbackHandler(application, request, **kwargs)

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:

------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:

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

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 _process_multipart_data(). If not, just adds the chunk to internal in-memory buffer.

Parameters:chunk – chunk of data received from Tornado
delete(*args, **kwargs)

Takes care of defining the new request body if necessary and forwarding the current request and changed body to the fallback.

get(*args, **kwargs)

Takes care of defining the new request body if necessary and forwarding the current request and changed body to the fallback.

head(*args, **kwargs)

Takes care of defining the new request body if necessary and forwarding the current request and changed body to the fallback.

is_multipart()

Checks whether this request is a multipart request

options(*args, **kwargs)

Takes care of defining the new request body if necessary and forwarding the current request and changed body to the fallback.

patch(*args, **kwargs)

Takes care of defining the new request body if necessary and forwarding the current request and changed body to the fallback.

post(*args, **kwargs)

Takes care of defining the new request body if necessary and forwarding the current request and changed body to the fallback.

prepare()

Prepares the processing of the request. If it’s a request that may contain a request body (as defined in 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.

put(*args, **kwargs)

Takes care of defining the new request body if necessary and forwarding the current request and changed body to the fallback.

class octoprint.server.util.tornado.UrlProxyHandler(application, request, **kwargs)

tornado.web.RequestHandler 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 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.
class octoprint.server.util.tornado.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:

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.

static environ(request, body=None)

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.

Parameters:
  • request – the tornado.httpserver.HTTPServerRequest to derive the WSGI environment from
  • body – an optional body to use as wsgi.input instead of request.body, can be a string or a stream
octoprint.server.util.tornado.access_validation_factory(app, login_manager, validator)

Creates an access validation wrapper using the supplied validator.

Parameters:validator – the access validator to use inside the validation wrapper
Returns:an access validator taking a request as parameter and performing the request validation
octoprint.server.util.tornado.fix_ioloop_scheduling()

This monkey patches tornado’s :meth:tornado.ioloop.PeriodicCallback._schedule_next method so it no longer blocks for long times on slow machines (RPi) when the system time happens to change by a large amount (e.g. due to the first ever contact to an NTP server).

Patch by @nosyjoe on Github. See this PR against tornado: https://github.com/tornadoweb/tornado/pull/1290

octoprint.server.util.tornado.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.

Parameters: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.
Returns:a request path validator taking a request path as parameter and performing the request validation