octoprint.server
- exception octoprint.server.CannotStartServerException
- class octoprint.server.OctoPrintAnonymousIdentity
octoprint.server.util
- 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 forOrigin
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.get_api_key(request: Request | tornado.httputil.HTTPServerRequest) str | None
Extracts the API key from the given request.
The request may be a Flask or Tornado request object. Attempts will be made to read the API key from the “apikey” request parameter, the “X-Api-Key” header, or the “Authorization” header in “Bearer” mode.
- Parameters:
request – the request object, either a Flask or a Tornado request
- Returns:
the API key, or None if not found
- Return type:
- octoprint.server.util.get_user_for_apikey(apikey, remote_address: str | None = None) User | None
Tries to find a user based on the given API key.
Will only perform any action if the API key is not None and not empty.
If the API key is the cli key and the client’s address is a loopback address, the CLI user will be returned.
If the API key is a user key, the user will be returned.
If the API key is neither, the key will be passed to all registered key validators and the first non-None result will be returned.
- Parameters:
- Returns:
the user found, or None if none was found
- Return type:
- octoprint.server.util.get_user_for_authorization_header(request: Request, header: str = 'Authorization') User | None
Tries to find a user based on the Authorization request header.
Will only perform any action if the trustBasicAuthentication setting is enabled.
If configured accordingly, will also check if the password used for the Basic Authentication matches the one stored for the user.
- Parameters:
request – the request object
header (str) – the header to check for the authorization header, defaults to “Authorization”
- octoprint.server.util.get_user_for_remote_user_header(request: Request) User | None
Tries to find a user based on the configured remote user request header.
Will only perform any action if the trustRemoteUser setting is enabled.
- 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.noCachingExceptGetResponseHandler(resp)
after_request
handler for blueprints which shall set no caching headers on their responses to any requests that are not sent with methodGET
.
- octoprint.server.util.noCachingResponseHandler(resp)
after_request
handler for blueprints which shall set no caching headers on their responses.Sets
Cache-Control
,Pragma
andExpires
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.
octoprint.server.util.flask
- class octoprint.server.util.flask.LessSimpleCache(threshold=500, default_timeout=300)
Slightly improved version of
SimpleCache
.Setting
default_timeout
ortimeout
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 alsoFalse
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 ofpickle.PickleError
.- Return type:
boolean
- class octoprint.server.util.flask.OctoPrintFlaskRequest(environ, *args, **kwargs)
-
- 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: Iterable[bytes] | bytes | Iterable[str] | str | None = None, status: int | str | HTTPStatus | None = None, headers: Mapping[str, str | Iterable[str]] | Iterable[tuple[str, str]] | None = None, mimetype: str | None = None, content_type: str | None = None, direct_passthrough: bool = False)
- delete_cookie(key, path='/', domain=None)
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”.
- set_cookie(key, value='', *args, **kwargs)
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 domainwww.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: App)
- 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 thedefault
,ensure_ascii
, andsort_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()
returnsTrue
.
- should_set_cookie(app, session)
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 theSESSION_REFRESH_EACH_REQUEST
config is true, the cookie is always set.This check is usually skipped if the session was deleted.
Added 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 ofbundle
should be written.target
may be a relative or absolute path, and is usually taking from theBundle.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.ReverseProxyInfo(*, client_ip: str, server_protocol: str, server_name: str, server_port: int, server_path: str, cookie_suffix: str, trusted_proxies: List[str] = [], headers: Dict[str, str] = {})
- model_computed_fields: ClassVar[Dict[str, ComputedFieldInfo]] = {}
A dictionary of computed field names and their corresponding ComputedFieldInfo objects.
- model_config: ClassVar[ConfigDict] = {}
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- model_fields: ClassVar[Dict[str, FieldInfo]] = {'client_ip': FieldInfo(annotation=str, required=True), 'cookie_suffix': FieldInfo(annotation=str, required=True), 'headers': FieldInfo(annotation=Dict[str, str], required=False, default={}), 'server_name': FieldInfo(annotation=str, required=True), 'server_path': FieldInfo(annotation=str, required=True), 'server_port': FieldInfo(annotation=int, required=True), 'server_protocol': FieldInfo(annotation=str, required=True), 'trusted_proxies': FieldInfo(annotation=List[str], required=False, default=[])}
Metadata about the fields defined on the model, mapping of field names to [FieldInfo][pydantic.fields.FieldInfo] objects.
This replaces Model.__fields__ from Pydantic V1.
- 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: 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 beFalse
.- 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:
- 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.get_cookie_suffix(request)
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()
andlogin_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 theContent-Length
of the request against the configured maximum utilizesmax_body_sizes
anddefault_max_body_size
as a fallback.
- class octoprint.server.util.tornado.CustomHTTP1ConnectionParameters(*args, **kwargs)
An implementation of
tornado.http1connection.HTTP1ConnectionParameters
that adds two new parametersmax_body_sizes
anddefault_max_body_size
.For a description of these please see the documentation of
CustomHTTPServer
above.
- class octoprint.server.util.tornado.CustomHTTP1ServerConnection(stream: IOStream, params: HTTP1ConnectionParameters | None = None, context: object | None = None)
A custom implementation of
tornado.http1connection.HTTP1ServerConnection
which utilizes aCustomHTTP1Connection
instead of atornado.http1connection.HTTP1Connection
in_server_request_loop
. The implementation logic is otherwise the same astornado.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 aCustomHTTP1ConnectionParameters
instance instead oftornado.http1connection.HTTP1ConnectionParameters
which is supplied with the two new constructor argumentsmax_body_sizes
andmax_default_body_size
and the creation of aCustomHTTP1ServerConnection
instead of atornado.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 frommax_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 thedefault_filename
keyword parameter). Defaults toNone
.as_attachment (bool) – Whether to serve requested files with
Content-Disposition: attachment
header (True
) or not. Defaults toFalse
.allow_client_caching (bool) – Whether to allow the client to cache (by not setting any
Cache-Control
orExpires
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 withself.request
as parameter which contains the full tornado request object. Should raise atornado.web.HTTPError
if access is not allowed in which case the request will not be further processed. Defaults toNone
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 atornado.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 toNone
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 byget_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.Added 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.
Added 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 thetornado.application
logger).Added 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 configuredcontent_type
.- Parameters:
- 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 totornado.web.FallbackHandler
which fetches any files contained in the request bodies of content typemultipart
, stores them in temporary files and supplies thefallback
with the file’sname
,content_type
,path
andsize
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 thefallback
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
andLocation
will be copied over.If
as_attachment
is set to True,Content-Disposition
will be set toattachment
. Ifbasename
is set including the attachment’sfilename
attribute will be set to the base name followed by the extension guessed based on the MIME type from theContent-Type
header of the response. If no extension can be guessed nofilename
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 toFalse
.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 withself.request
as parameter which contains the full tornado request object. Should raise atornado.web.HTTPError
if access is not allowed in which case the request will not be further processed. Defaults toNone
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__
andenviron
methods have been adjusted to allow for an optionally suppliedbody
argument which is then used forwsgi.input
.Additionally, some headers can be added or removed from the response by supplying
forced_headers
andremoved_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 populatingwsgi.input
can be supplied (either a string or a stream). If not supplied,request.body
will be wrapped into aio.BytesIO
stream and used instead.- Parameters:
request – the
tornado.httpserver.HTTPServerRequest
to derive the WSGI environment frombody – an optional body to use as
wsgi.input
instead ofrequest.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 frombody – an optional body to use as
wsgi.input
instead ofrequest.body
, can be a string or a streamfuture – 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_tornado_xheader_handling()
This fixes tornado.httpserver._HTTPRequestContext._apply_xheaders to only use “X-Forwarded-For” header for rewriting the
remote_ip
field, utilizing the set of trusted downstreams, instead of blindly trustingX-Real-Ip
, and to also fetch the scheme from “X-Forwarded-Proto” if available.
- 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