octoprint.server

exception octoprint.server.CannotStartServerException
class octoprint.server.OctoPrintAnonymousIdentity

octoprint.server.util

exception octoprint.server.util.InvalidApiKeyException
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.csrfRequestHandler()

before_request handler for blueprints which checks for CRFS double token on relevant requests & methods.

octoprint.server.util.csrfResponseHandler(resp)

after_request handler for updating the CSRF cookie on each response.

octoprint.server.util.has_permissions(*permissions)

Determines if the current user (either from the session, api key or authorization header) has all of the requested permissions.

Parameters

*permissions – list of all permissions required to pass the check

Returns: True if the user has all permissions, False otherwise

octoprint.server.util.loginFromApiKeyRequestHandler()

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

App session keys are handled as anonymous keys here and ignored.

TODO 1.11.0: Do we still need this with load_user_from_request in place?

octoprint.server.util.loginFromAuthorizationHeaderRequestHandler()

before_request handler for creating login sessions based on the Authorization header.

TODO 1.11.0: Do we still need this with load_user_from_request in place?

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.require_fresh_login_with(permissions=None, user_id=None)

Requires a login with fresh credentials.

Parameters
  • permissions – list of all permissions required to pass the check

  • user_id – required user to pass the check

Returns: a flask redirect response to return if a login is required, or None

octoprint.server.util.require_login(*permissions)

Returns a redirect response to the login view if the permission requirements are not met.

Parameters

*permissions – a list of permissions required to pass the check

Returns: a flask redirect response to return if a login is required, or None

octoprint.server.util.require_login_with(permissions=None, user_id=None)

Requires a login with the given permissions and/or user id.

Parameters
  • permissions – list of all permissions required to pass the check

  • user_id – required user to pass the check

Returns: a flask redirect response to return if a login is required, or None

octoprint.server.util.validate_local_redirect(url, allowed_paths)

Validates the given local redirect URL against the given allowed paths.

An url is valid for a local redirect if it has neither scheme nor netloc defined, and its path is one of the given allowed paths.

Parameters
  • url (str) – URL to validate

  • allowed_paths (List[str]) – List of allowed paths, only paths contained or prefixed (if allowed path ends with “*”) will be considered valid.

Returns

Whether the url passed validation or not.

Return type

bool

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.

add(key, value, timeout=None)

Works like set() but does not overwrite the values of already existing keys.

Parameters
  • key – the key to set

  • value – the value for the key

  • timeout – the cache timeout for the key in seconds (if not specified, it uses the default timeout). A timeout of 0 indicates that the cache never expires.

Returns

Same as set(), but also False for already existing keys.

Return type

boolean

delete(key)

Delete key from the cache.

Parameters

key – the key to delete.

Returns

Whether the key existed and has been deleted.

Return type

boolean

get(key)

Look up key in the cache and return the value for it.

Parameters

key – the key to be looked up.

Returns

The value if it exists and is readable, else None.

set(key, value, timeout=None)

Add a new key/value to the cache (overwrites value, if key already exists in the cache).

Parameters
  • key – the key to set

  • value – the value for the key

  • timeout – the cache timeout for the key in seconds (if not specified, it uses the default timeout). A timeout of 0 indicates that the cache never expires.

Returns

True if key has been updated, False for backend errors. Pickling errors, however, will raise a subclass of pickle.PickleError.

Return type

boolean

class octoprint.server.util.flask.OctoPrintFlaskRequest(environ, *args, **kwargs)
property cookies

A dict with the contents of all cookies transmitted with the request.

property server_name

Short cut to the request’s server name header

property server_port

Short cut to the request’s server port header

class octoprint.server.util.flask.OctoPrintFlaskResponse(response: Optional[Union[Iterable[bytes], bytes, Iterable[str], str]] = None, status: Optional[Union[int, str, HTTPStatus]] = None, headers: Optional[Union[Mapping[str, Union[str, int, Iterable[Union[str, int]]]], Iterable[Tuple[str, Union[str, int]]]]] = None, mimetype: Optional[str] = None, content_type: Optional[str] = None, direct_passthrough: bool = False)

Delete a cookie. Fails silently if key doesn’t exist.

Parameters
  • key – the key (name) of the cookie to be deleted.

  • path – if the cookie that should be deleted was limited to a path, the path has to be defined here.

  • domain – if the cookie that should be deleted was limited to a domain, that domain has to be defined here.

  • secure – If True, the cookie will only be available via HTTPS.

  • httponly – Disallow JavaScript access to the cookie.

  • samesite – Limit the scope of the cookie to only be attached to requests that are “same-site”.

response: Union[Iterable[str], Iterable[bytes]]

The response body to send as the WSGI iterable. A list of strings or bytes represents a fixed-length response, any other iterable is a streaming response. Strings are encoded to bytes as UTF-8.

Do not set to a plain string or bytes, that will cause sending the response to be very inefficient as it will iterate one byte at a time.

Sets a cookie.

A warning is raised if the size of the cookie header exceeds max_cookie_size, but the header will still be set.

Parameters
  • key – the key (name) of the cookie to be set.

  • value – the value of the cookie.

  • max_age – should be a number of seconds, or None (default) if the cookie should last only as long as the client’s browser session.

  • expires – should be a datetime object or UNIX timestamp.

  • path – limits the cookie to a given path, per default it will span the whole domain.

  • domain – if you want to set a cross-domain cookie. For example, domain=".example.com" will set a cookie that is readable by the domain www.example.com, foo.example.com etc. Otherwise, a cookie will only be readable by the domain that set it.

  • secure – If True, the cookie will only be available via HTTPS.

  • httponly – Disallow JavaScript access to the cookie.

  • samesite – Limit the scope of the cookie to only be attached to requests that are “same-site”.

class octoprint.server.util.flask.OctoPrintJsonProvider(app: Flask)
static default(object_)
dumps(obj: Any, **kwargs: Any) str

Serialize data as JSON to a string.

Keyword arguments are passed to json.dumps(). Sets some parameter defaults from the default, ensure_ascii, and sort_keys attributes.

Parameters
  • obj – The data to serialize.

  • kwargs – Passed to json.dumps().

class octoprint.server.util.flask.OctoPrintSessionInterface
save_session(app, session, response)

This is called at the end of each request, after generating a response, before removing the request context. It is skipped if is_null_session() returns True.

Used by session backends to determine if a Set-Cookie header should be set for this session cookie for this response. If the session has been modified, the cookie is set. If the session is permanent and the SESSION_REFRESH_EACH_REQUEST config is true, the cookie is always set.

This check is usually skipped if the session was deleted.

New in version 0.11.

class octoprint.server.util.flask.PluginAssetResolver
resolve_output_to_path(ctx, target, bundle)

Given target, this has to return the absolute filesystem path to which the output file of bundle should be written.

target may be a relative or absolute path, and is usually taking from the Bundle.output property.

If a version-placeholder is used (%(version)s, it is still unresolved at this point.

split_prefix(ctx, item)

See if item has blueprint prefix, return (directory, rel_path).

class octoprint.server.util.flask.PrefixAwareJinjaEnvironment(*args, **kwargs)
join_path(template, parent)

Join a template with the parent. By default all the lookups are relative to the loader root so this method returns the template parameter unchanged, but if the paths should be relative to the parent template, this function can be used to calculate the real template name.

Subclasses may override this method and implement template path joining here.

class octoprint.server.util.flask.SettingsCheckUpdater
build_done(bundle, ctx)

This will be called once a bundle has been successfully built.

needs_rebuild(bundle, ctx)

Returns True if the given bundle needs to be rebuilt, False otherwise.

octoprint.server.util.flask.check_lastmodified(lastmodified: Union[int, float, datetime]) bool

Compares the provided lastmodified value with the value of the If-Modified-Since header.

If lastmodified is an int or float, it’s assumed to be a Unix timestamp and converted to a timezone aware datetime instance in UTC.

If lastmodified is a datetime instance, it needs to be timezone aware or the result will always be False.

Parameters

lastmodified (Union[int, float, datetime]) – The last modified value to compare against

Raises

ValueError – If anything but an int, float or datetime instance is passed

Returns

true if the values indicate that the document is still up to date

Return type

bool

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.

Request specific suffix for set and read cookies

We need this because cookies are not port-specific and we don’t want to overwrite our session and other cookies from one OctoPrint instance on our machine with those of another one who happens to listen on the same address albeit a different port or script root.

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

Retrieves the current flask user from the request context. Uses API key if available, otherwise the current user session if available.

Parameters

request – flask request from which to retrieve the current user

Returns

the user (might be an anonymous user)

octoprint.server.util.flask.make_api_error(message, status)

Helper to generate API error responses in JSON format.

Turns something like make_api_error("Not Found", 404) into a JSON response with body {"error": "Not Found"}.

Parameters
  • message – The error message to put into the response

  • status – The HTTP status code

Returns: a flask response to return to the client

octoprint.server.util.flask.make_text_response(message, status)

Helper to generate basic text responses.

Response will have the provided message as body, the provided status code, and a content type of “text/plain”.

Parameters
  • message – The message in the response body

  • status – The HTTP status code

Returns:

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

If you decorate a view with this, it will ensure that first setup has been done for OctoPrint’s Access Control.

If OctoPrint’s Access Control has not been setup yet (indicated by the userManager not reporting that its 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.permission_and_fresh_credentials_validator(request, permission)

Validates that the given request is made by an authorized user, identified either by API key or existing Flask session, and that the credentials have been checked recently if it’s a Flask session.

Must be executed in an existing Flask request context!

Parameters
  • request – The Flask request object

  • request – The required permission

octoprint.server.util.flask.permission_validator(request, permission)

Validates that the given request is made by an authorized 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

  • request – The required permission

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

If you decorate a view with this, it will ensure that only users who entered their password recently in this login session are allowed to proceed. Otherwise it will cause a HTTP 403 status code to be returned by the decorated resource.

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

This combines no_firstrun_access() and login_required.

octoprint.server.util.sockjs

class octoprint.server.util.sockjs.ThreadSafeSession(conn, server, session_id, expiry=None)
remove_handler(handler)

Detach active handler from the session

handler

Handler to remove

set_handler(handler, start_heartbeat=True)

Set active handler for the session

handler

Associate active Tornado handler with the session

start_heartbeat

Should session start heartbeat immediately

octoprint.server.util.tornado

class octoprint.server.util.tornado.CorsSupportMixin(application: Application, request: HTTPServerRequest, **kwargs: Any)

tornado.web.RequestHandler mixin that makes sure to set CORS headers similarly to the Flask backed API endpoints.

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.

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: IOStream, params: Optional[HTTP1ConnectionParameters] = None, context: Optional[object] = 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(*args: Any, **kwargs: Any)

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.

handle_stream(stream, address)

Override to handle a new .IOStream from an incoming connection.

This method may be a coroutine; if so any exceptions it raises asynchronously will be logged. Accepting of incoming connections will not be blocked by this coroutine.

If this TCPServer is configured for SSL, handle_stream may be called before the SSL handshake has completed. Use .SSLIOStream.wait_for_handshake if you need to verify the client’s certificate or use NPN/ALPN.

Changed in version 4.2: Added the option for this method to be a coroutine.

initialize(*args, **kwargs)
class octoprint.server.util.tornado.DeprecatedEndpointHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)

tornado.web.RequestHandler that redirects to another url and logs a deprecation warning.

Parameters

url (str) – URL to which to redirect

initialize(url)
class octoprint.server.util.tornado.DynamicZipBundleHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)
initialize(path_validation=None, path_processor=None, as_attachment=True, attachment_name=None, access_validation=None, compress=False)
class octoprint.server.util.tornado.GeneratingDataHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)

A RequestHandler that generates data from a generator function and returns it to the client.

Parameters
  • generator (function) – A generator function that returns the data to be written to the client. The function will be called without any parameters.

  • content_type (str) – The content type with which to respond. Defaults to text/plain

  • as_attachment (bool | str) – Whether to serve files with Content-Disposition: attachment header (True) or not. Defaults to False. If a string is given it will be used as the filename of the attachment.

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

initialize(generator=None, content_type='text/plain', as_attachment=False, access_validation=None)
class octoprint.server.util.tornado.GlobalHeaderTransform(request)
class octoprint.server.util.tornado.LargeResponseHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)

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.

  • 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

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.

get_content_type()

Returns the Content-Type header to be used for this request.

New in version 3.1.

classmethod get_content_version(abspath)

Returns a version string for the resource at the given path.

This class method may be overridden by subclasses. The default implementation is a SHA-512 hash of the file’s contents.

New in version 3.1.

initialize(path, default_filename=None, as_attachment=False, allow_client_caching=True, access_validation=None, path_validation=None, etag_generator=None, name_generator=None, mime_type_guesser=None, is_pre_compressed=False, stream_body=False)
property original_absolute_path

The path of the uncompressed file corresponding to the compressed file

set_extra_headers(path)

For subclass to add extra headers to the response

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)

class octoprint.server.util.tornado.RequestlessExceptionLoggingMixin(application: Application, request: HTTPServerRequest, **kwargs: Any)
log_exception(typ, value, tb, *args, **kwargs)

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.

class octoprint.server.util.tornado.StaticDataHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)

tornado.web.RequestHandler 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

initialize(data='', content_type='text/plain')
class octoprint.server.util.tornado.StaticZipBundleHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)
initialize(files=None, as_attachment=True, attachment_name=None, access_validation=None, compress=False)
class octoprint.server.util.tornado.SystemInfoBundleHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)
initialize(access_validation=None)
class octoprint.server.util.tornado.UploadStorageFallbackHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)

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

async delete(*args, **kwargs)

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

async get(*args, **kwargs)

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

async head(*args, **kwargs)

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

initialize(fallback, file_prefix='tmp', file_suffix='', path=None, suffixes=None)
is_multipart()

Checks whether this request is a multipart request

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.

async options(*args, **kwargs)

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

async patch(*args, **kwargs)

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

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

async 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: Application, request: HTTPServerRequest, **kwargs: Any)

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.

initialize(url=None, as_attachment=False, basename=None, access_validation=None)
class octoprint.server.util.tornado.WebcamSnapshotHandler(application: Application, request: HTTPServerRequest, **kwargs: Any)

GeneratingDataHandler that returns a snapshot from the configured webcam.

Parameters
  • as_attachment (bool | str) – Whether to serve files with Content-Disposition: attachment header (True) or not. Defaults to False. If a string is given it will be used as the filename of the attachment.

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

initialize(as_attachment=False, access_validation=None)
class octoprint.server.util.tornado.WsgiInputContainer(wsgi_application, executor=None, 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.

Additionally, some headers can be added or removed from the response by supplying forced_headers and removed_headers arguments. forced_headers will be added to the response, removed_headers will be removed.

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

async handle_request(request, body=None, future=None)

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

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

  • future – a future to complete after the request has been handled

octoprint.server.util.tornado.access_validation_factory(app, validator, *args)

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

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

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

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