-
+
{{ _('Cleanup') }}
diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py
index b3949b0ff..a30f161ff 100644
--- a/src/octoprint/plugins/softwareupdate/__init__.py
+++ b/src/octoprint/plugins/softwareupdate/__init__.py
@@ -1012,8 +1012,11 @@ class SoftwareUpdatePlugin(
}
)
except exceptions.ConfigurationInvalid as e:
- return flask.make_response(
- "Update not properly configured, can't proceed: {}".format(e), 500
+ flask.abort(
+ 500,
+ description="Update not properly configured, can't proceed: {}".format(
+ e
+ ),
)
def etag():
@@ -1078,30 +1081,31 @@ class SoftwareUpdatePlugin(
and not self._settings.get_boolean(["ignore_throttled"])
):
# currently throttled, we refuse to run
- return flask.make_response(
- "System is currently throttled, refusing to update "
- "anything due to possible stability issues",
+ flask.abort(
409,
+ description="System is currently throttled, refusing to update "
+ "anything due to possible stability issues",
)
if self._printer.is_printing() or self._printer.is_paused():
# do not update while a print job is running
- return flask.make_response("Printer is currently printing or paused", 409)
+ flask.abort(409, description="Printer is currently printing or paused")
if not self._environment_supported:
- return flask.make_response(
- "Direct updates are not supported in this Python environment", 409
+ flask.abort(
+ 409,
+ description="Direct updates are not supported in this Python environment",
)
if not self._storage_sufficient:
- return flask.make_response("Not enough free disk space for updating", 409)
+ flask.abort(409, description="Not enough free disk space for updating")
if "application/json" not in flask.request.headers["Content-Type"]:
- return flask.make_response("Expected content-type JSON", 400)
+ flask.abort(400, description="Expected content-type JSON")
json_data = flask.request.get_json(silent=True)
if json_data is None:
- return flask.make_response("Invalid JSON", 400)
+ flask.abort(400, description="Invalid JSON")
if "targets" in json_data or "checks" in json_data:
targets = list(
@@ -1124,7 +1128,7 @@ class SoftwareUpdatePlugin(
def configure_update(self):
json_data = flask.request.get_json(silent=True)
if json_data is None:
- return flask.make_response("Invalid JSON", 400)
+ flask.abort(400)
checks = self._get_configured_checks()
@@ -1796,7 +1800,9 @@ class SoftwareUpdatePlugin(
populated_check = self._populated_check(target, check)
try:
- self._logger.info("Starting update of %s to %s..." % (target, target_version))
+ self._logger.info(
+ "Starting update of {} to {}...".format(target, target_version)
+ )
self._send_client_message(
"updating",
{
@@ -1813,7 +1819,9 @@ class SoftwareUpdatePlugin(
target, populated_check, target_version, log_cb=self._log, online=online
)
target_result = ("success", update_result)
- self._logger.info("Update of %s to %s successful!" % (target, target_version))
+ self._logger.info(
+ "Update of {} to {} successful!".format(target, target_version)
+ )
trigger_event(True)
except exceptions.UnknownUpdateType:
diff --git a/src/octoprint/plugins/softwareupdate/updaters/pip.py b/src/octoprint/plugins/softwareupdate/updaters/pip.py
index 1c9716e34..e10e15131 100644
--- a/src/octoprint/plugins/softwareupdate/updaters/pip.py
+++ b/src/octoprint/plugins/softwareupdate/updaters/pip.py
@@ -98,7 +98,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True, forc
target_version=target_version, target=target_version
)
- logger.debug("Target: %s, executing pip install %s" % (target, install_arg))
+ logger.debug("Target: {}, executing pip install {}".format(target, install_arg))
pip_args = ["--disable-pip-version-check", "install", install_arg, "--no-cache-dir"]
pip_kwargs = {
"env": {"PYTHONWARNINGS": b"ignore:DEPRECATION::pip._internal.cli.base_command"}
diff --git a/src/octoprint/plugins/softwareupdate/updaters/update_script.py b/src/octoprint/plugins/softwareupdate/updaters/update_script.py
index c27eb4b77..2bf31153f 100644
--- a/src/octoprint/plugins/softwareupdate/updaters/update_script.py
+++ b/src/octoprint/plugins/softwareupdate/updaters/update_script.py
@@ -79,7 +79,7 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
if pre_update_script is not None:
logger.debug(
- "Target: %s, running pre-update script: %s" % (target, pre_update_script)
+ "Target: {}, running pre-update script: {}".format(target, pre_update_script)
)
try:
caller.checked_call(pre_update_script, cwd=folder)
@@ -100,7 +100,9 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
force="true" if force_exact_version else "false",
)
- logger.debug("Target %s, running update script: %s" % (target, update_command))
+ logger.debug(
+ "Target {}, running update script: {}".format(target, update_command)
+ )
caller.checked_call(update_command, cwd=folder)
except CommandlineError as e:
@@ -116,7 +118,9 @@ def perform_update(target, check, target_version, log_cb=None, online=True):
if post_update_script is not None:
logger.debug(
- "Target: %s, running post-update script %s..." % (target, post_update_script)
+ "Target: {}, running post-update script {}...".format(
+ target, post_update_script
+ )
)
try:
caller.checked_call(post_update_script, cwd=folder)
diff --git a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py
index 9dbb37d1f..66c298426 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/bitbucket_commit.py
@@ -90,6 +90,8 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
current is not None and current == remote_commit
) or remote_commit is None
- logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
+ logger.debug(
+ "Target: {}, local: {}, remote: {}".format(target, current, remote_commit)
+ )
return information, is_current
diff --git a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py
index 2840f6784..c5f226018 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/commandline.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/commandline.py
@@ -56,6 +56,8 @@ def get_latest(target, check, online=True, *args, **kwargs):
logger = logging.getLogger(
"octoprint.plugins.softwareupdate.version_checks.github_commit"
)
- logger.debug("Target: %s, local: %s, remote: %s" % (target, local_name, remote_name))
+ logger.debug(
+ "Target: {}, local: {}, remote: {}".format(target, local_name, remote_name)
+ )
return information, is_current
diff --git a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py
index 72f431b7f..96ab26569 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/git_commit.py
@@ -98,7 +98,7 @@ def get_latest(target, check, online=True, *args, **kwargs):
"octoprint.plugins.softwareupdate.version_checks.git_commit"
)
logger.debug(
- "Target: %s, local: %s, remote: %s" % (target, local_commit, remote_commit)
+ "Target: {}, local: {}, remote: {}".format(target, local_commit, remote_commit)
)
return information, is_current
diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py
index 42e548c56..56187b0fe 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/github_commit.py
@@ -94,6 +94,8 @@ def get_latest(target, check, online=True, credentials=None, *args, **kwargs):
current is not None and current == remote_commit
) or remote_commit is None
- logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_commit))
+ logger.debug(
+ "Target: {}, local: {}, remote: {}".format(target, current, remote_commit)
+ )
return information, is_current
diff --git a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py
index 0f6ef6228..19690a3c4 100644
--- a/src/octoprint/plugins/softwareupdate/version_checks/github_release.py
+++ b/src/octoprint/plugins/softwareupdate/version_checks/github_release.py
@@ -355,7 +355,7 @@ def get_latest(
"release_notes": release_notes,
}
- logger.debug("Target: %s, local: %s, remote: %s" % (target, current, remote_tag))
+ logger.debug("Target: {}, local: {}, remote: {}".format(target, current, remote_tag))
return information, _is_current(
information, compare_type, custom=custom_compare, force_base=force_base
diff --git a/src/octoprint/plugins/virtual_printer/virtual.py b/src/octoprint/plugins/virtual_printer/virtual.py
index 08d75bad2..756a79656 100644
--- a/src/octoprint/plugins/virtual_printer/virtual.py
+++ b/src/octoprint/plugins/virtual_printer/virtual.py
@@ -701,7 +701,10 @@ class VirtualPrinter:
def _gcode_M117(self, data: str) -> None:
# we'll just use this to echo a message, to allow playing around with pause triggers
if self._echoOnM117:
- self._send("echo:%s" % re.search(r"M117\s+(.*)", data).group(1))
+ try:
+ self._send("echo:%s" % re.search(r"M117\s+(.*)", data).group(1))
+ except AttributeError:
+ self._send("echo:")
def _gcode_M155(self, data: str) -> None:
matchS = re.search(r"S([0-9]+)", data)
diff --git a/src/octoprint/printer/profile.py b/src/octoprint/printer/profile.py
index b1c28a5aa..cd7d44831 100644
--- a/src/octoprint/printer/profile.py
+++ b/src/octoprint/printer/profile.py
@@ -549,7 +549,7 @@ class PrinterProfileManager:
self._logger.exception(
"Error while trying to save profile %s" % profile["id"]
)
- raise SaveError("Cannot save profile %s: %s" % (profile["id"], str(e)))
+ raise SaveError("Cannot save profile {}: {}".format(profile["id"], str(e)))
def _remove_from_path(self, path):
try:
diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py
index 929b73657..9d1d2eadf 100644
--- a/src/octoprint/server/__init__.py
+++ b/src/octoprint/server/__init__.py
@@ -37,6 +37,7 @@ from flask_login import ( # noqa: F401
)
from watchdog.observers import Observer
from watchdog.observers.polling import PollingObserver
+from werkzeug.exceptions import HTTPException
import octoprint.util
import octoprint.util.net
@@ -60,8 +61,8 @@ except ImportError:
fcntl = None
SUCCESS = {}
-NO_CONTENT = ("", 204)
-NOT_MODIFIED = ("Not Modified", 304)
+NO_CONTENT = ("", 204, {"Content-Type": "text/plain"})
+NOT_MODIFIED = ("Not Modified", 304, {"Content-Type": "text/plain"})
app = Flask("octoprint")
@@ -745,10 +746,13 @@ class Server:
lambda path: not octoprint.util.is_hidden_path(path), status_code=404
)
}
+
+ valid_timelapse = lambda path: not octoprint.util.is_hidden_path(
+ path
+ ) and octoprint.timelapse.valid_timelapse(path)
timelapse_path_validator = {
"path_validation": util.tornado.path_validation_factory(
- lambda path: not octoprint.util.is_hidden_path(path)
- and octoprint.timelapse.valid_timelapse(path),
+ valid_timelapse,
status_code=404,
)
}
@@ -759,12 +763,23 @@ class Server:
status_code=400,
)
}
+
+ valid_log = (
+ lambda path: not octoprint.util.is_hidden_path(path)
+ and path.endswith(".log")
+ and os.path.realpath(os.path.abspath(path)).startswith(
+ settings().getBaseFolder("logs")
+ )
+ )
+ log_path_validator = {
+ "path_validation": util.tornado.path_validation_factory(
+ valid_log,
+ status_code=404,
+ )
+ }
logs_path_validator = {
"path_validation": util.tornado.path_validation_factory(
- lambda path: not octoprint.util.is_hidden_path(path)
- and os.path.realpath(os.path.abspath(path)).startswith(
- settings().getBaseFolder("logs")
- ),
+ valid_log,
status_code=400,
)
}
@@ -839,6 +854,7 @@ class Server:
},
download_handler_kwargs,
log_permission_validator,
+ log_path_validator,
),
),
# zipped log file bundles
@@ -1411,7 +1427,7 @@ class Server:
result.add(locale.language)
if locale.territory:
# if a territory is specified, add that too
- result.add("%s_%s" % (locale.language, locale.territory))
+ result.add("{}_{}".format(locale.language, locale.territory))
return result
@@ -1714,12 +1730,19 @@ class Server:
# do not remove or the index view won't be found
import octoprint.server.views # noqa: F401
from octoprint.server.api import api
+ from octoprint.server.util.flask import make_api_error
blueprints = OrderedDict()
blueprints["/api"] = api
+ json_errors = ["/api"]
# also register any blueprints defined in BlueprintPlugins
- blueprints.update(self._prepare_blueprint_plugins())
+ (
+ blueprint_from_plugins,
+ api_prefixes_from_plugins,
+ ) = self._prepare_blueprint_plugins()
+ blueprints.update(blueprint_from_plugins)
+ json_errors += api_prefixes_from_plugins
# and register a blueprint for serving the static files of asset plugins which are not blueprint plugins themselves
blueprints.update(self._prepare_asset_plugins())
@@ -1731,8 +1754,16 @@ class Server:
for url_prefix, blueprint in blueprints.items():
app.register_blueprint(blueprint, url_prefix=url_prefix)
+ @app.errorhandler(HTTPException)
+ def _handle_api_error(ex):
+ if any(map(lambda x: request.path.startswith(x), json_errors)):
+ return make_api_error(ex.description, ex.code)
+ else:
+ return ex
+
def _prepare_blueprint_plugins(self):
blueprints = OrderedDict()
+ api_prefixes = []
blueprint_plugins = octoprint.plugin.plugin_manager().get_implementations(
octoprint.plugin.BlueprintPlugin
@@ -1740,6 +1771,9 @@ class Server:
for plugin in blueprint_plugins:
try:
blueprint, prefix = self._prepare_blueprint_plugin(plugin)
+ api_prefixes += map(
+ lambda x: prefix + x, plugin.get_blueprint_api_prefixes()
+ )
blueprints[prefix] = blueprint
except Exception:
self._logger.exception(
@@ -1749,7 +1783,7 @@ class Server:
)
continue
- return blueprints
+ return blueprints, api_prefixes
def _prepare_asset_plugins(self):
blueprints = OrderedDict()
diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py
index 6d3ff2204..59323a036 100644
--- a/src/octoprint/server/api/__init__.py
+++ b/src/octoprint/server/api/__init__.py
@@ -7,6 +7,7 @@ import logging
from flask import (
Blueprint,
+ Response,
abort,
current_app,
g,
@@ -77,24 +78,40 @@ def pluginData(name):
lambda p: p._identifier == name, octoprint.plugin.SimpleApiPlugin
)
if not api_plugins:
- return make_response("Not found", 404)
+ abort(404)
if len(api_plugins) > 1:
- return make_response(
- "More than one api provider registered for {name}, can't proceed".format(
- name=name
- ),
- 500,
- )
+ abort(500, description="More than one api provider registered, can't proceed")
try:
api_plugin = api_plugins[0]
if api_plugin.is_api_adminonly() and not current_user.is_admin:
- return make_response("Forbidden", 403)
+ abort(403)
response = api_plugin.on_api_get(request)
if response is not None:
+ message = (
+ "Rewriting response from {} to use abort(msg, code) - please "
+ "consider upgrading the implementation accordingly".format(name)
+ )
+ if (
+ isinstance(response, Response)
+ and response.mimetype == "text/html"
+ and response.status_code >= 300
+ ):
+ # this actually looks like an error response
+ logging.getLogger(__name__).info(message)
+ abort(response.status_code, description=response.data)
+ elif (
+ isinstance(response, tuple)
+ and len(response) == 2
+ and isinstance(response[0], (str, bytes))
+ and response[1] >= 300
+ ):
+ # this actually looks like an error response
+ logging.getLogger(__name__).info(message)
+ abort(response[1], response[0])
return response
return NO_CONTENT
except HTTPException:
@@ -117,24 +134,19 @@ def pluginCommand(name):
)
if not api_plugins:
- return make_response("Not found", 404)
+ abort(400)
if len(api_plugins) > 1:
- return make_response(
- "More than one api provider registered for {name}, can't proceed".format(
- name=name
- ),
- 500,
- )
+ abort(500, description="More than one api provider registered, can't proceed")
api_plugin = api_plugins[0]
try:
valid_commands = api_plugin.get_api_commands()
if valid_commands is None:
- return make_response("Method not allowed", 405)
+ abort(405)
if api_plugin.is_api_adminonly() and not Permissions.ADMIN.can():
- return make_response("Forbidden", 403)
+ abort(403)
command, data, response = get_json_command_from_request(request, valid_commands)
if response is not None:
@@ -250,14 +262,6 @@ def wizardFinish():
# ~~ system state
-@api.route("/state", methods=["GET"])
-@no_firstrun_access
-def apiPrinterState():
- return make_response(
- ("/api/state has been deprecated, use /api/printer instead", 405, [])
- )
-
-
@api.route("/version", methods=["GET"])
@Permissions.STATUS.require(403)
def apiVersion():
@@ -299,7 +303,7 @@ def login():
if user is not None:
if octoprint.server.userManager.check_password(username, password):
if not user.is_active:
- return make_response(("Your account is deactivated", 403, []))
+ abort(403)
user = octoprint.server.userManager.login_user(user)
session["usersession.id"] = user.session
@@ -336,12 +340,12 @@ def login():
return r
- return make_response(("User unknown or password incorrect", 403, []))
+ abort(403)
elif "passive" in data:
return passive_login()
- return make_response("Neither user and pass attributes nor passive flag present", 400)
+ abort(400, description="Neither user and pass attributes nor passive flag present")
@api.route("/logout", methods=["POST"])
@@ -585,12 +589,7 @@ def _test_url(data):
try:
timeout = float(data["timeout"])
except Exception:
- return make_response(
- "{!r} is not a valid value for timeout (must be int or float)".format(
- data["timeout"]
- ),
- 400,
- )
+ abort(400, description="timeout is invalid")
if "validSsl" in data:
valid_ssl = data["validSsl"] in valid_boolean_trues
@@ -614,13 +613,13 @@ def _test_url(data):
if "content_type_whitelist" in data:
if not isinstance(data["content_type_whitelist"], (list, tuple)):
- return make_response("content_type_whitelist must be a list of mime types")
+ abort(400, description="content_type_whitelist must be a list of mime types")
content_type_whitelist = list(
map(util.parse_mime_type, data["content_type_whitelist"])
)
if "content_type_blacklist" in data:
if not isinstance(data["content_type_whitelist"], (list, tuple)):
- return make_response("content_type_blacklist must be a list of mime types")
+ abort(400, description="content_type_blacklist must be a list of mime types")
content_type_blacklist = list(
map(util.parse_mime_type, data["content_type_blacklist"])
)
@@ -701,28 +700,18 @@ def _test_server(data):
try:
port = int(data["port"])
except Exception:
- return make_response(
- "{!r} is not a valid value for port (must be int)".format(data["port"]), 400
- )
+ abort(400, description="Invalid value for port")
timeout = 3.05
if "timeout" in data:
try:
timeout = float(data["timeout"])
except Exception:
- return make_response(
- "{!r} is not a valid value for timeout (must be int or float)".format(
- data["timeout"]
- ),
- 400,
- )
+ abort(400, description="Invalid value for timeout")
protocol = data.get("protocol", "tcp")
if protocol not in ("tcp", "udp"):
- return make_response(
- "{!r} is not a valid value for protocol, must be tcp or udp".format(protocol),
- 400,
- )
+ abort(400, description="Invalid value for protocol")
from octoprint.util import server_reachable
diff --git a/src/octoprint/server/api/access.py b/src/octoprint/server/api/access.py
index 21d7659e9..a41badce9 100644
--- a/src/octoprint/server/api/access.py
+++ b/src/octoprint/server/api/access.py
@@ -2,9 +2,8 @@ __author__ = "Marc Hannappel
"
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2017 The OctoPrint Project - Released under terms of the AGPLv3 License"
-from flask import abort, jsonify, make_response, request
+from flask import abort, jsonify, request
from flask_login import current_user
-from werkzeug.exceptions import BadRequest
import octoprint.access.groups as groups
import octoprint.access.users as users
@@ -36,19 +35,16 @@ def get_groups():
@Permissions.SETTINGS.require(403)
def add_group():
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content-type JSON", 400)
+ abort(400, description="Expected content-type JSON")
- try:
- data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ data = request.get_json()
if "key" not in data:
- return make_response("Missing mandatory key field", 400)
+ abort(400, description="key is missing")
if "name" not in data:
- return make_response("Missing mandatory name field", 400)
+ abort(400, description="name is missing")
if "permissions" not in data:
- return make_response("Missing mandatory permissions field", 400)
+ abort(400, description="permissions are missing")
key = data["key"]
name = data["name"]
@@ -87,12 +83,9 @@ def get_group(key):
@Permissions.SETTINGS.require(403)
def update_group(key):
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content-type JSON", 400)
+ abort(400, description="Expected content-type JSON")
- try:
- data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ data = request.get_json()
try:
kwargs = {}
@@ -146,22 +139,18 @@ def get_users():
@Permissions.SETTINGS.require(403)
def add_user():
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content-type JSON", 400)
-
- try:
- data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Expected content-type JSON")
+ data = request.get_json()
if data is None:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Malformed JSON body in request")
if "name" not in data:
- return make_response("Missing mandatory name field", 400)
+ abort(400, description="name is missing")
if "password" not in data:
- return make_response("Missing mandatory password field", 400)
+ abort(400, description="password is missing")
if "active" not in data:
- return make_response("Missing mandatory active field", 400)
+ abort(400, description="active is missing")
name = data["name"]
password = data["password"]
@@ -204,12 +193,12 @@ def update_user(username):
user = userManager.find_user(username)
if user is not None:
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content-type JSON", 400)
+ abort(400, description="Expected content-type JSON")
- try:
- data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ data = request.get_json()
+
+ if data is None:
+ abort(400, description="Malformed JSON body in request")
# change groups
if "groups" in data:
@@ -221,9 +210,6 @@ def update_user(username):
permissions = data["permissions"]
userManager.change_user_permissions(username, permissions)
- if data is None:
- return make_response("Malformed JSON body in request", 400)
-
# change activation
if "active" in data:
userManager.change_user_activation(
@@ -258,27 +244,24 @@ def change_password_for_user(username):
and (current_user.get_name() == username or current_user.is_admin)
):
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content-type JSON", 400)
+ abort(400, description="Expected content-type JSON")
- try:
- data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ data = request.get_json()
if data is None:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Malformed JSON body in request")
if "password" not in data or not data["password"]:
- return make_response("password is missing from request", 400)
+ abort(400, description="password is missing")
try:
userManager.change_user_password(username, data["password"])
except users.UnknownUser:
- return make_response(("Unknown user: %s" % username, 404, []))
+ abort(404)
return jsonify(SUCCESS)
else:
- return make_response(("Forbidden", 403, []))
+ abort(403)
@api.route("/access/users//settings", methods=["GET"])
@@ -292,12 +275,12 @@ def get_settings_for_user(username):
and not current_user.has_permission(Permissions.ADMIN)
)
):
- return make_response("Forbidden", 403)
+ abort(403)
try:
return jsonify(userManager.get_all_user_settings(username))
except users.UnknownUser:
- return make_response("Unknown user: %s" % username, 404)
+ abort(404)
@api.route("/access/users//settings", methods=["PATCH"])
@@ -311,21 +294,18 @@ def change_settings_for_user(username):
and not current_user.has_permission(Permissions.ADMIN)
)
):
- return make_response("Forbidden", 403)
+ abort(403)
- try:
- data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ data = request.get_json()
if data is None:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Malformed JSON body in request")
try:
userManager.change_user_settings(username, data)
return jsonify(SUCCESS)
except users.UnknownUser:
- return make_response("Unknown user: %s" % username, 404)
+ abort(404)
@api.route("/access/users//apikey", methods=["DELETE"])
@@ -342,10 +322,10 @@ def delete_apikey_for_user(username):
try:
userManager.delete_api_key(username)
except users.UnknownUser:
- return make_response(("Unknown user: %s" % username, 404, []))
+ abort(404)
return jsonify(SUCCESS)
else:
- return make_response(("Forbidden", 403, []))
+ abort(403)
@api.route("/access/users//apikey", methods=["POST"])
@@ -365,10 +345,10 @@ def generate_apikey_for_user(username):
try:
apikey = userManager.generate_api_key(username)
except users.UnknownUser:
- return make_response(("Unknown user: %s" % username, 404, []))
+ abort(404)
return jsonify({"apikey": apikey})
else:
- return make_response(("Forbidden", 403, []))
+ abort(403)
def _to_external_permissions(*permissions):
diff --git a/src/octoprint/server/api/connection.py b/src/octoprint/server/api/connection.py
index 0475aec2b..ed612cd63 100644
--- a/src/octoprint/server/api/connection.py
+++ b/src/octoprint/server/api/connection.py
@@ -2,7 +2,7 @@ __author__ = "Gina Hรคuรge "
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
-from flask import jsonify, make_response, request
+from flask import abort, jsonify, request
from octoprint.access.permissions import Permissions
from octoprint.server import NO_CONTENT, printer, printerProfileManager
@@ -46,15 +46,15 @@ def connectionCommand():
if "port" in data:
port = data["port"]
if port not in connection_options["ports"] and port != "AUTO":
- return make_response("Invalid port: %s" % port, 400)
+ abort(400, description="port is invalid")
if "baudrate" in data:
baudrate = data["baudrate"]
if baudrate not in connection_options["baudrates"] and baudrate != 0:
- return make_response("Invalid baudrate: %d" % baudrate, 400)
+ abort(400, description="baudrate is invalid")
if "printerProfile" in data:
printerProfile = data["printerProfile"]
if not printerProfileManager.exists(printerProfile):
- return make_response("Invalid printer profile: %s" % printerProfile, 400)
+ abort(400, description="printerProfile is invalid")
if "save" in data and data["save"]:
settings().set(["serial", "port"], port)
settings().setInt(["serial", "baudrate"], baudrate)
diff --git a/src/octoprint/server/api/files.py b/src/octoprint/server/api/files.py
index b06ba6611..4ad77af5e 100644
--- a/src/octoprint/server/api/files.py
+++ b/src/octoprint/server/api/files.py
@@ -8,7 +8,7 @@ import os
import threading
import psutil
-from flask import jsonify, make_response, request, url_for
+from flask import abort, jsonify, make_response, request, url_for
import octoprint.filemanager
import octoprint.filemanager.storage
@@ -177,7 +177,7 @@ def readGcodeFiles():
)
def readGcodeFilesForOrigin(origin):
if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
- return make_response("Unknown origin: %s" % origin, 404)
+ abort(404)
filter = request.values.get("filter", False)
recursive = request.values.get("recursive", "false") in valid_boolean_trues
@@ -213,7 +213,10 @@ def readGcodeFilesForOrigin(origin):
)
def readGcodeFile(target, filename):
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
- return make_response("Unknown target: %s" % target, 404)
+ abort(404)
+
+ if filename != fileManager.sanitize(target, filename):
+ abort(404)
recursive = False
if "recursive" in request.values:
@@ -221,7 +224,7 @@ def readGcodeFile(target, filename):
file = _getFileDetails(target, filename, recursive=recursive)
if not file:
- return make_response("File not found on '%s': %s" % (target, filename), 404)
+ abort(404)
return jsonify(file)
@@ -447,7 +450,7 @@ def uploadGcodeFile(target):
)
if input_upload_name in request.values and input_upload_path in request.values:
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
- return make_response("Unknown target: %s" % target, 404)
+ abort(404)
upload = octoprint.filemanager.util.DiskFileWrapper(
request.values[input_upload_name], request.values[input_upload_path]
@@ -461,12 +464,12 @@ def uploadGcodeFile(target):
try:
userdata = json.loads(request.values["userdata"])
except Exception:
- return make_response("userdata contains invalid JSON", 400)
+ abort(400, description="userdata contains invalid JSON")
if target == FileDestinations.SDCARD and not settings().getBoolean(
["feature", "sdSupport"]
):
- return make_response("SD card support is disabled", 404)
+ abort(404)
sd = target == FileDestinations.SDCARD
selectAfterUpload = (
@@ -486,14 +489,12 @@ def uploadGcodeFile(target):
printer.is_operational()
and not (printer.is_printing() or printer.is_paused())
):
- return make_response(
- "Can not upload to SD card, printer is either not operational or already busy",
+ abort(
409,
+ description="Can not upload to SD card, printer is either not operational or already busy",
)
if not printer.is_sd_ready():
- return make_response(
- "Can not upload to SD card, not yet initialized", 409
- )
+ abort(409, description="Can not upload to SD card, not yet initialized")
# determine future filename of file to be uploaded, abort if it can't be uploaded
try:
@@ -511,9 +512,7 @@ def uploadGcodeFile(target):
futureFilename = None
if futureFilename is None:
- return make_response(
- "Can not upload file %s, wrong format?" % upload.filename, 415
- )
+ abort(415, description="Can not upload file, wrong format?")
if "path" in request.values and request.values["path"]:
# we currently only support uploads to sdcard via local, so first target is local instead of "target"
@@ -530,10 +529,9 @@ def uploadGcodeFile(target):
)
if not printer.can_modify_file(futureFullPathInStorage, sd):
- return make_response(
- "Trying to overwrite file that is currently being printed: %s"
- % futureFullPath,
+ abort(
409,
+ description="Trying to overwrite file that is currently being printed",
)
reselect = printer.is_current_file(futureFullPathInStorage, sd)
@@ -591,16 +589,9 @@ def uploadGcodeFile(target):
)
except octoprint.filemanager.storage.StorageError as e:
if e.code == octoprint.filemanager.storage.StorageError.INVALID_FILE:
- return make_response(
- 'Could not upload the file "{}", invalid type'.format(
- upload.filename
- ),
- 400,
- )
+ abort(400, description="Could not upload file, invalid type")
else:
- return make_response(
- 'Could not upload the file "{}"'.format(upload.filename), 500
- )
+ abort(500, description="Could not upload file")
if octoprint.filemanager.valid_file_type(added_file, "stl"):
filename = added_file
@@ -685,13 +676,13 @@ def uploadGcodeFile(target):
foldername = request.values["foldername"]
if target not in [FileDestinations.LOCAL]:
- return make_response("Unknown target: %s" % target, 400)
+ abort(400, description="target is invalid")
canonPath, canonName = fileManager.canonicalize(target, foldername)
futurePath = fileManager.sanitize_path(target, canonPath)
futureName = fileManager.sanitize_name(target, canonName)
if not futureName or not futurePath:
- return make_response("Can't create a folder with an empty name", 400)
+ abort(400, description="folder name is empty")
if "path" in request.values and request.values["path"]:
futurePath = fileManager.sanitize_path(
@@ -700,10 +691,7 @@ def uploadGcodeFile(target):
futureFullPath = fileManager.join_path(target, futurePath, futureName)
if octoprint.filemanager.valid_file_type(futureName):
- return make_response(
- "Can't create a folder named %s, please try another name" % futureName,
- 409,
- )
+ abort(409, description="Can't create folder, please try another name")
try:
added_folder = fileManager.add_folder(
@@ -711,11 +699,9 @@ def uploadGcodeFile(target):
)
except octoprint.filemanager.storage.StorageError as e:
if e.code == octoprint.filemanager.storage.StorageError.INVALID_DIRECTORY:
- return make_response(
- "Could not create folder {}, invalid directory".format(futureName)
- )
+ abort(400, description="Could not create folder, invalid directory")
else:
- return make_response("Could not create folder {}".format(futureName))
+ abort(500, description="Could not create folder")
location = url_for(
".readGcodeFile",
@@ -735,14 +721,17 @@ def uploadGcodeFile(target):
return r
else:
- return make_response("No file to upload and no folder to create", 400)
+ abort(400, description="No file to upload and no folder to create")
@api.route("/files//", methods=["POST"])
@no_firstrun_access
def gcodeFileCommand(filename, target):
if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
- return make_response("Unknown target: %s" % target, 404)
+ abort(404)
+
+ if filename != fileManager.sanitize(target, filename):
+ abort(404)
# valid file commands, dict mapping command name to mandatory parameters
valid_commands = {
@@ -762,31 +751,28 @@ def gcodeFileCommand(filename, target):
if command == "select":
with Permissions.FILES_SELECT.require(403):
if not _verifyFileExists(target, filename):
- return make_response(
- "File not found on '%s': %s" % (target, filename), 404
- )
+ abort(404)
# selects/loads a file
if not octoprint.filemanager.valid_file_type(filename, type="machinecode"):
- return make_response(
- "Cannot select {filename} for printing, not a machinecode file".format(
- **locals()
- ),
+ abort(
415,
+ description="Cannot select file for printing, not a machinecode file",
)
if not printer.is_ready():
- return make_response(
- "Printer is already printing, cannot select a new file", 409
+ abort(
+ 409,
+ description="Printer is already printing, cannot select a new file",
)
printAfterLoading = False
if "print" in data and data["print"] in valid_boolean_trues:
with Permissions.PRINT.require(403):
if not printer.is_operational():
- return make_response(
- "Printer is not operational, cannot directly start printing",
+ abort(
409,
+ description="Printer is not operational, cannot directly start printing",
)
printAfterLoading = True
@@ -801,9 +787,7 @@ def gcodeFileCommand(filename, target):
elif command == "slice":
with Permissions.SLICE.require(403):
if not _verifyFileExists(target, filename):
- return make_response(
- "File not found on '%s': %s" % (target, filename), 404
- )
+ abort(404)
try:
if "slicer" in data:
@@ -816,14 +800,9 @@ def gcodeFileCommand(filename, target):
slicer_instance = slicingManager.get_slicer("cura")
else:
- return make_response(
- "Cannot slice {filename}, no slicer available".format(**locals()),
- 415,
- )
- except octoprint.slicing.UnknownSlicer as e:
- return make_response(
- "Slicer {slicer} is not available".format(slicer=e.slicer), 400
- )
+ abort(415, description="Cannot slice file, no slicer available")
+ except octoprint.slicing.UnknownSlicer:
+ abort(404)
if not any(
[
@@ -833,9 +812,7 @@ def gcodeFileCommand(filename, target):
)
]
):
- return make_response(
- "Cannot slice {filename}, not a model file".format(**locals()), 415
- )
+ abort(415, description="Cannot slice file, not a model file")
cores = psutil.cpu_count()
if (
@@ -844,11 +821,9 @@ def gcodeFileCommand(filename, target):
and (cores is None or cores < 2)
):
# slicer runs on same device as OctoPrint, slicing while printing is hence disabled
- return make_response(
- "Cannot slice on {slicer} while printing on single core systems or systems of unknown core count due to performance reasons".format(
- **locals()
- ),
+ abort(
409,
+ description="Cannot slice on this slicer while printing on single core systems or systems of unknown core count due to performance reasons",
)
if "destination" in data and data["destination"]:
@@ -892,10 +867,9 @@ def gcodeFileCommand(filename, target):
and currentOrigin == target
and (printer.is_printing() or printer.is_paused())
):
- make_response(
- "Trying to slice into file that is currently being printed: %s"
- % full_path,
+ abort(
409,
+ description="Trying to slice into file that is currently being printed",
)
if "profile" in data and data["profile"]:
@@ -925,17 +899,18 @@ def gcodeFileCommand(filename, target):
select_after_slicing = False
if "select" in data and data["select"] in valid_boolean_trues:
if not printer.is_operational():
- return make_response(
- "Printer is not operational, cannot directly select for printing",
+ abort(
409,
+ description="Printer is not operational, cannot directly select for printing",
)
select_after_slicing = True
print_after_slicing = False
if "print" in data and data["print"] in valid_boolean_trues:
if not printer.is_operational():
- return make_response(
- "Printer is not operational, cannot directly start printing", 409
+ abort(
+ 409,
+ description="Printer is not operational, cannot directly start printing",
)
select_after_slicing = print_after_slicing = True
@@ -977,11 +952,8 @@ def gcodeFileCommand(filename, target):
),
)
except octoprint.slicing.UnknownProfile:
- return make_response(
- "Profile {profile} doesn't exist".format(**locals()), 400
- )
+ abort(404, description="Unknown profile")
- files = {}
location = url_for(
".readGcodeFile", target=target, filename=full_path, _external=True
)
@@ -1007,9 +979,7 @@ def gcodeFileCommand(filename, target):
elif command == "analyse":
with Permissions.FILES_UPLOAD.require(403):
if not _verifyFileExists(target, filename):
- return make_response(
- "File not found on '%s': %s" % (target, filename), 404
- )
+ abort(404)
printer_profile = None
if "printerProfile" in data and data["printerProfile"]:
@@ -1018,24 +988,18 @@ def gcodeFileCommand(filename, target):
if not fileManager.analyse(
target, filename, printer_profile_id=printer_profile
):
- return make_response(
- "No analysis possible for {} on {}".format(filename, target), 400
- )
+ abort(400, description="No analysis possible")
elif command == "copy" or command == "move":
with Permissions.FILES_UPLOAD.require(403):
# Copy and move are only possible on local storage
if target not in [FileDestinations.LOCAL]:
- return make_response(
- "Unsupported target for {}: {}".format(command, target), 400
- )
+ abort(400, description="Unsupported target for {}".format(command))
if not _verifyFileExists(target, filename) and not _verifyFolderExists(
target, filename
):
- return make_response(
- "File or folder not found on {}: {}".format(target, filename), 404
- )
+ abort(404)
path, name = fileManager.split_path(target, filename)
@@ -1056,22 +1020,14 @@ def gcodeFileCommand(filename, target):
if _verifyFileExists(target, destination) or _verifyFolderExists(
target, destination
):
- return make_response(
- "File or folder does already exist on {}: {}".format(
- target, destination
- ),
- 409,
- )
+ abort(409, description="File or folder does already exist")
is_file = fileManager.file_exists(target, filename)
is_folder = fileManager.folder_exists(target, filename)
if not (is_file or is_folder):
- return make_response(
- "{} on {} is neither file or folder, can't {}".format(
- filename, target, command
- ),
- 400,
+ abort(
+ 400, description="Neither file nor folder, can't {}".format(command)
)
if command == "copy":
@@ -1079,12 +1035,7 @@ def gcodeFileCommand(filename, target):
if _verifyFileExists(target, destination) or _verifyFolderExists(
target, destination
):
- return make_response(
- "File or folder does already exist on {}: {}".format(
- target, destination
- ),
- 409,
- )
+ abort(409, description="File or folder does already exist")
if is_file:
fileManager.copy_file(target, filename, destination)
@@ -1094,11 +1045,9 @@ def gcodeFileCommand(filename, target):
elif command == "move":
with Permissions.FILES_DELETE.require(403):
if _isBusy(target, filename):
- return make_response(
- "Trying to move a file or folder that is currently in use: {}".format(
- filename
- ),
+ abort(
409,
+ description="Trying to move a file or folder that is currently in use",
)
# destination already there AND not ourselves (= display rename)? error...
@@ -1106,12 +1055,7 @@ def gcodeFileCommand(filename, target):
_verifyFileExists(target, destination)
or _verifyFolderExists(target, destination)
) and sanitized_destination != filename:
- return make_response(
- "File or folder does already exist on {}: {}".format(
- target, destination
- ),
- 409,
- )
+ abort(409, description="File or folder does already exist")
# deselect the file if it's currently selected
currentOrigin, currentFilename = _getCurrentFile()
@@ -1152,21 +1096,20 @@ def gcodeFileCommand(filename, target):
@no_firstrun_access
@Permissions.FILES_DELETE.require(403)
def deleteGcodeFile(filename, target):
+ if filename != fileManager.sanitize(target, filename):
+ abort(404)
+
if not _verifyFileExists(target, filename) and not _verifyFolderExists(
target, filename
):
- return make_response(
- "File/Folder not found on '%s': %s" % (target, filename), 404
- )
+ abort(404)
+
+ if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
+ abort(404)
if _verifyFileExists(target, filename):
- if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]:
- return make_response("Unknown target: %s" % target, 400)
-
if _isBusy(target, filename):
- return make_response(
- "Trying to delete a file that is currently in use: %s" % filename, 409
- )
+ abort(409, description="Trying to delete a file that is currently in use")
# deselect the file if it's currently selected
currentOrigin, currentPath = _getCurrentFile()
@@ -1184,14 +1127,10 @@ def deleteGcodeFile(filename, target):
fileManager.remove_file(target, filename)
elif _verifyFolderExists(target, filename):
- if target not in [FileDestinations.LOCAL]:
- return make_response("Unknown target: %s" % target, 400)
-
if _isBusy(target, filename):
- return make_response(
- "Trying to delete a folder that contains a file that is currently in use: %s"
- % filename,
+ abort(
409,
+ description="Trying to delete a folder that contains a file that is currently in use",
)
# deselect the file if it's currently selected
diff --git a/src/octoprint/server/api/job.py b/src/octoprint/server/api/job.py
index be202e0d3..4de446326 100644
--- a/src/octoprint/server/api/job.py
+++ b/src/octoprint/server/api/job.py
@@ -2,7 +2,7 @@ __author__ = "Gina Hรคuรge "
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
-from flask import jsonify, make_response, request
+from flask import abort, jsonify, request
from octoprint.access.permissions import Permissions
from octoprint.server import NO_CONTENT, current_user, printer
@@ -14,7 +14,7 @@ from octoprint.server.util.flask import get_json_command_from_request, no_firstr
@no_firstrun_access
def controlJob():
if not printer.is_operational():
- return make_response("Printer is not operational", 409)
+ abort(409, description="Printer is not operational")
valid_commands = {"start": [], "restart": [], "pause": [], "cancel": []}
@@ -31,22 +31,23 @@ def controlJob():
with Permissions.PRINT.require(403):
if command == "start":
if activePrintjob:
- return make_response(
- "Printer already has an active print job, did you mean 'restart'?",
+ abort(
409,
+ description="Printer already has an active print job, did you mean 'restart'?",
)
printer.start_print(tags=tags, user=user)
elif command == "restart":
if not printer.is_paused():
- return make_response(
- "Printer does not have an active print job or is not paused", 409
+ abort(
+ 409,
+ description="Printer does not have an active print job or is not paused",
)
printer.start_print(tags=tags, user=user)
elif command == "pause":
if not activePrintjob:
- return make_response(
- "Printer is neither printing nor paused, 'pause' command cannot be performed",
+ abort(
409,
+ description="Printer is neither printing nor paused, 'pause' command cannot be performed",
)
action = data.get("action", "toggle")
if action == "toggle":
@@ -56,17 +57,12 @@ def controlJob():
elif action == "resume":
printer.resume_print(tags=tags, user=user)
else:
- return make_response(
- "Unknown action '{}', allowed values for action parameter are 'pause', 'resume' and 'toggle'".format(
- action
- ),
- 400,
- )
+ abort(400, description="Unknown action")
elif command == "cancel":
if not activePrintjob:
- return make_response(
- "Printer is neither printing nor paused, 'cancel' command cannot be performed",
+ abort(
409,
+ description="Printer is neither printing nor paused, 'cancel' command cannot be performed",
)
printer.cancel_print(tags=tags, user=user)
return NO_CONTENT
diff --git a/src/octoprint/server/api/languages.py b/src/octoprint/server/api/languages.py
index 9cac453bd..7815cfdbd 100644
--- a/src/octoprint/server/api/languages.py
+++ b/src/octoprint/server/api/languages.py
@@ -10,7 +10,7 @@ import zipfile
from collections import defaultdict
from os import scandir
-from flask import jsonify, make_response, request
+from flask import abort, jsonify, request
from flask_babel import Locale
from octoprint.access.permissions import Permissions
@@ -127,7 +127,7 @@ def uploadLanguagePack():
input_name + "." + settings().get(["server", "uploads", "nameSuffix"])
)
if input_upload_path not in request.values or input_upload_name not in request.values:
- return make_response("No file included", 400)
+ abort(400, description="No file included")
upload_name = request.values[input_upload_name]
upload_path = request.values[input_upload_path]
@@ -138,8 +138,9 @@ def uploadLanguagePack():
)
)
if not len(exts):
- return make_response(
- "File doesn't have a valid extension for a language pack archive", 400
+ abort(
+ 400,
+ description="File doesn't have a valid extension for a language pack archive",
)
target_path = settings().getBaseFolder("translations")
@@ -149,7 +150,7 @@ def uploadLanguagePack():
elif zipfile.is_zipfile(upload_path):
_unpack_uploaded_zipfile(upload_path, target_path)
else:
- return make_response("Neither zip file nor tarball included", 400)
+ abort(400, description="Neither zip file nor tarball included")
return getInstalledLanguagePacks()
diff --git a/src/octoprint/server/api/printer.py b/src/octoprint/server/api/printer.py
index 8fc1f8d45..b892df317 100644
--- a/src/octoprint/server/api/printer.py
+++ b/src/octoprint/server/api/printer.py
@@ -4,8 +4,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import re
-from flask import Response, jsonify, make_response, request
-from werkzeug.exceptions import BadRequest
+from flask import Response, abort, jsonify, request
from octoprint.access.permissions import Permissions
from octoprint.printer import UnknownScript
@@ -21,7 +20,7 @@ from octoprint.settings import settings, valid_boolean_trues
@Permissions.STATUS.require(403)
def printerState():
if not printer.is_operational():
- return make_response("Printer is not operational", 409)
+ abort(409, description="Printer is not operational")
# process excludes
excludes = []
@@ -71,7 +70,7 @@ def printerState():
@Permissions.CONTROL.require(403)
def printerToolCommand():
if not printer.is_operational():
- return make_response("Printer is not operational", 409)
+ abort(409, description="Printer is not operational")
valid_commands = {
"select": ["tool"],
@@ -92,9 +91,7 @@ def printerToolCommand():
if command == "select":
tool = data["tool"]
if not isinstance(tool, str) or re.match(validation_regex, tool) is None:
- return make_response("Invalid tool: %s" % tool, 400)
- if not tool.startswith("tool"):
- return make_response("Invalid tool for selection: %s" % tool, 400)
+ abort(400, description="tool is invalid")
printer.change_tool(tool, tags=tags)
@@ -106,11 +103,9 @@ def printerToolCommand():
validated_values = {}
for tool, value in targets.items():
if re.match(validation_regex, tool) is None:
- return make_response(
- "Invalid target for setting temperature: %s" % tool, 400
- )
+ abort(400, description="targets contains invalid tool")
if not isinstance(value, (int, float)):
- return make_response("Not a number for %s: %r" % (tool, value), 400)
+ abort(400, description="targets contains invalid value")
validated_values[tool] = value
# perform the actual temperature commands
@@ -125,15 +120,9 @@ def printerToolCommand():
validated_values = {}
for tool, value in offsets.items():
if re.match(validation_regex, tool) is None:
- return make_response(
- "Invalid target for setting temperature: %s" % tool, 400
- )
- if not isinstance(value, (int, float)):
- return make_response("Not a number for %s: %r" % (tool, value), 400)
- if not -50 <= value <= 50:
- return make_response(
- "Offset %s not in range [-50, 50]: %f" % (tool, value), 400
- )
+ abort(400, description="offsets contains invalid tool")
+ if not isinstance(value, (int, float)) or not -50 <= value <= 50:
+ abort(400, description="offsets contains invalid value")
validated_values[tool] = value
# set the offsets
@@ -143,22 +132,22 @@ def printerToolCommand():
elif command == "extrude":
if printer.is_printing():
# do not extrude when a print job is running
- return make_response("Printer is currently printing", 409)
+ abort(409, description="Printer is currently printing")
amount = data["amount"]
speed = data.get("speed", None)
if not isinstance(amount, (int, float)):
- return make_response("Not a number for extrusion amount: %r" % amount, 400)
+ abort(400, description="amount is invalid")
printer.extrude(amount, speed=speed, tags=tags)
elif command == "flowrate":
factor = data["factor"]
if not isinstance(factor, (int, float)):
- return make_response("Not a number for flow rate: %r" % factor, 400)
+ abort(400, description="factor is invalid")
try:
printer.flow_rate(factor, tags=tags)
- except ValueError as e:
- return make_response("Invalid value for flow rate: %s" % str(e), 400)
+ except ValueError:
+ abort(400, description="factor is invalid")
return NO_CONTENT
@@ -168,7 +157,7 @@ def printerToolCommand():
@Permissions.STATUS.require(403)
def printerToolState():
if not printer.is_operational():
- return make_response("Printer is not operational", 409)
+ abort(409, description="Printer is not operational")
return jsonify(_get_temperature_data(_keep_tools))
@@ -181,10 +170,10 @@ def printerToolState():
@Permissions.CONTROL.require(403)
def printerBedCommand():
if not printer.is_operational():
- return make_response("Printer is not operational", 409)
+ abort(409, description="Printer is not operational")
if not printerProfileManager.get_current_or_default()["heatedBed"]:
- return make_response("Printer does not have a heated bed", 409)
+ abort(409, description="Printer does not have a heated bed")
valid_commands = {"target": ["target"], "offset": ["offset"]}
command, data, response = get_json_command_from_request(request, valid_commands)
@@ -199,7 +188,7 @@ def printerBedCommand():
# make sure the target is a number
if not isinstance(target, (int, float)):
- return make_response("Not a number: %r" % target, 400)
+ abort(400, description="target is invalid")
# perform the actual temperature command
printer.set_temperature("bed", target, tags=tags)
@@ -209,10 +198,8 @@ def printerBedCommand():
offset = data["offset"]
# make sure the offset is valid
- if not isinstance(offset, (int, float)):
- return make_response("Not a number: %r" % offset, 400)
- if not -50 <= offset <= 50:
- return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
+ if not isinstance(offset, (int, float)) or not -50 <= offset <= 50:
+ abort(400, description="offset is invalid")
# set the offsets
printer.set_temperature_offset({"bed": offset})
@@ -225,10 +212,10 @@ def printerBedCommand():
@Permissions.STATUS.require(403)
def printerBedState():
if not printer.is_operational():
- return make_response("Printer is not operational", 409)
+ abort(409, description="Printer is not operational")
if not printerProfileManager.get_current_or_default()["heatedBed"]:
- return make_response("Printer does not have a heated bed", 409)
+ abort(409, description="Printer does not have a heated bed")
data = _get_temperature_data(_keep_bed)
if isinstance(data, Response):
@@ -245,10 +232,10 @@ def printerBedState():
@Permissions.CONTROL.require(403)
def printerChamberCommand():
if not printer.is_operational():
- return make_response("Printer is not operational", 409)
+ abort(409, description="Printer is not operational")
if not printerProfileManager.get_current_or_default()["heatedChamber"]:
- return make_response("Printer does not have a heated chamber", 409)
+ abort(409, description="Printer does not have a heated chamber")
valid_commands = {"target": ["target"], "offset": ["offset"]}
command, data, response = get_json_command_from_request(request, valid_commands)
@@ -263,7 +250,7 @@ def printerChamberCommand():
# make sure the target is a number
if not isinstance(target, (int, float)):
- return make_response("Not a number: %r" % target, 400)
+ abort(400, description="target is invalid")
# perform the actual temperature command
printer.set_temperature("chamber", target, tags=tags)
@@ -273,10 +260,8 @@ def printerChamberCommand():
offset = data["offset"]
# make sure the offset is valid
- if not isinstance(offset, (int, float)):
- return make_response("Not a number: %r" % offset, 400)
- if not -50 <= offset <= 50:
- return make_response("Offset not in range [-50, 50]: %f" % offset, 400)
+ if not isinstance(offset, (int, float)) or not -50 <= offset <= 50:
+ abort(400, description="offset is invalid")
# set the offsets
printer.set_temperature_offset({"chamber": offset})
@@ -289,10 +274,10 @@ def printerChamberCommand():
@Permissions.STATUS.require(403)
def printerChamberState():
if not printer.is_operational():
- return make_response("Printer is not operational", 409)
+ abort(409, description="Printer is not operational")
if not printerProfileManager.get_current_or_default()["heatedChamber"]:
- return make_response("Printer does not have a heated chamber", 409)
+ abort(409, description="Printer does not have a heated chamber")
data = _get_temperature_data(_keep_chamber)
if isinstance(data, Response):
@@ -315,7 +300,7 @@ def printerPrintheadCommand():
if not printer.is_operational() or (printer.is_printing() and command != "feedrate"):
# do not jog when a print job is running or we don't have a connection
- return make_response("Printer is not operational or currently printing", 409)
+ abort(409, description="Printer is not operational or currently printing")
tags = {"source:api", "api:printer.printhead"}
@@ -328,9 +313,7 @@ def printerPrintheadCommand():
if axis in data:
value = data[axis]
if not isinstance(value, (int, float)):
- return make_response(
- "Not a number for axis %s: %r" % (axis, value), 400
- )
+ abort(400, description="axis value is invalid")
validated_values[axis] = value
absolute = "absolute" in data and data["absolute"] in valid_boolean_trues
@@ -345,7 +328,7 @@ def printerPrintheadCommand():
axes = data["axes"]
for axis in axes:
if axis not in valid_axes:
- return make_response("Invalid axis: %s" % axis, 400)
+ abort(400, description="axis is invalid")
validated_values.append(axis)
# execute the home command
@@ -354,11 +337,11 @@ def printerPrintheadCommand():
elif command == "feedrate":
factor = data["factor"]
if not isinstance(factor, (int, float)):
- return make_response("Not a number for feed rate: %r" % factor, 400)
+ abort(400, description="factor is invalid")
try:
printer.feed_rate(factor, tags=tags)
- except ValueError as e:
- return make_response("Invalid value for feed rate: %s" % str(e), 400)
+ except ValueError:
+ abort(400, description="factor is invalid")
return NO_CONTENT
@@ -371,10 +354,10 @@ def printerPrintheadCommand():
@Permissions.CONTROL.require(403)
def printerSdCommand():
if not settings().getBoolean(["feature", "sdSupport"]):
- return make_response("SD support is disabled", 404)
+ abort(404, description="SD support is disabled")
if not printer.is_operational() or printer.is_printing() or printer.is_paused():
- return make_response("Printer is not operational or currently busy", 409)
+ abort(409, description="Printer is not operational or currently busy")
valid_commands = {"init": [], "refresh": [], "release": []}
command, data, response = get_json_command_from_request(request, valid_commands)
@@ -398,7 +381,7 @@ def printerSdCommand():
@Permissions.STATUS.require(403)
def printerSdState():
if not settings().getBoolean(["feature", "sdSupport"]):
- return make_response("SD support is disabled", 404)
+ abort(404, description="SD support is disabled")
return jsonify(ready=printer.is_sd_ready())
@@ -411,27 +394,22 @@ def printerSdState():
@Permissions.CONTROL.require(403)
def printerCommand():
if not printer.is_operational():
- return make_response("Printer is not operational", 409)
+ abort(409, description="Printer is not operational")
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content type JSON", 400)
+ abort(400, description="Expected content type JSON")
- try:
- data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ data = request.get_json()
if data is None:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Malformed JSON body in request")
if "command" in data and "commands" in data:
- return make_response("'command' and 'commands' are mutually exclusive", 400)
+ abort(400, description="'command' and 'commands' are mutually exclusive")
elif ("command" in data or "commands" in data) and "script" in data:
- return make_response(
- "'command'/'commands' and 'script' are mutually exclusive", 400
- )
+ abort(400, description="'command'/'commands' and 'script' are mutually exclusive")
elif not ("command" in data or "commands" in data or "script" in data):
- return make_response("Need one of 'command', 'commands' or 'script'", 400)
+ abort(400, description="Need one of 'command', 'commands' or 'script'")
parameters = {}
if "parameters" in data:
@@ -444,7 +422,7 @@ def printerCommand():
commands = [data["command"]]
else:
if not isinstance(data["commands"], (list, tuple)):
- return make_response("'commands' needs to be a list", 400)
+ abort(400, description="commands is invalid")
commands = data["commands"]
commandsToSend = []
@@ -465,7 +443,7 @@ def printerCommand():
try:
printer.script(script_name, context=context, tags=tags)
except UnknownScript:
- return make_response("Unknown script: {script_name}".format(**locals()), 404)
+ abort(404, description="Unknown script")
return NO_CONTENT
@@ -480,7 +458,7 @@ def getCustomControls():
def _get_temperature_data(preprocessor):
if not printer.is_operational():
- return make_response("Printer is not operational", 409)
+ abort(409, description="Printer is not operational")
tempData = printer.get_current_temperatures()
diff --git a/src/octoprint/server/api/printer_profiles.py b/src/octoprint/server/api/printer_profiles.py
index 149f383fb..55644eb45 100644
--- a/src/octoprint/server/api/printer_profiles.py
+++ b/src/octoprint/server/api/printer_profiles.py
@@ -5,8 +5,7 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import copy
-from flask import jsonify, make_response, request, url_for
-from werkzeug.exceptions import BadRequest
+from flask import abort, jsonify, request, url_for
from octoprint.access.permissions import Permissions
from octoprint.printer.profile import CouldNotOverwriteError, InvalidProfileError
@@ -56,18 +55,15 @@ def printerProfilesList():
@Permissions.SETTINGS.require(403)
def printerProfilesAdd():
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content-type JSON", 400)
+ abort(400, description="Expected content-type JSON")
- try:
- json_data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ json_data = request.get_json()
if json_data is None:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Malformed JSON body in request")
if "profile" not in json_data:
- return make_response("No profile included in request", 400)
+ abort(400, description="profile is missing")
base_profile = printerProfileManager.get_default()
if "basedOn" in json_data and isinstance(json_data["basedOn"], str):
@@ -91,25 +87,20 @@ def printerProfilesAdd():
profile = dict_merge(base_profile, new_profile)
if "id" not in profile:
- return make_response("Profile does not contain mandatory 'id' field", 400)
+ abort(400, description="profile.id is missing")
if "name" not in profile:
- return make_response("Profile does not contain mandatory 'name' field", 400)
+ abort(400, description="profile.name is missing")
try:
saved_profile = printerProfileManager.save(
profile, allow_overwrite=False, make_default=make_default, trigger_event=True
)
except InvalidProfileError:
- return make_response("Profile is invalid", 400)
+ abort(400, description="profile is invalid")
except CouldNotOverwriteError:
- return make_response(
- "Profile {} already exists and overwriting was not allowed".format(
- profile["id"]
- ),
- 400,
- )
+ abort(400, description="Profile already exists and overwriting was not allowed")
except Exception as e:
- return make_response("Could not save profile: %s" % str(e), 500)
+ abort(500, description="Could not save profile: %s" % str(e))
else:
return jsonify({"profile": _convert_profile(saved_profile)})
@@ -120,7 +111,7 @@ def printerProfilesAdd():
def printerProfilesGet(identifier):
profile = printerProfileManager.get(identifier)
if profile is None:
- return make_response("Unknown profile: %s" % identifier, 404)
+ abort(404)
else:
return jsonify(_convert_profile(profile))
@@ -131,13 +122,11 @@ def printerProfilesGet(identifier):
def printerProfilesDelete(identifier):
current_profile = printerProfileManager.get_current()
if current_profile and current_profile["id"] == identifier:
- return make_response(
- "Cannot delete currently selected profile: {}".format(identifier), 409
- )
+ abort(409, description="Cannot delete currently selected profile")
default_profile = printerProfileManager.get_default()
if default_profile and default_profile["id"] == identifier:
- return make_response("Cannot delete default profile: {}".format(identifier), 409)
+ abort(409, description="Cannot delete default profile")
printerProfileManager.remove(identifier, trigger_event=True)
return NO_CONTENT
@@ -148,18 +137,14 @@ def printerProfilesDelete(identifier):
@Permissions.SETTINGS.require(403)
def printerProfilesUpdate(identifier):
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content-type JSON", 400)
-
- try:
- json_data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Expected content-type JSON")
+ json_data = request.get_json()
if json_data is None:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Malformed JSON body in request")
if "profile" not in json_data:
- return make_response("No profile included in request", 400)
+ abort(400, description="profile missing")
profile = printerProfileManager.get(identifier)
if profile is None:
@@ -183,13 +168,11 @@ def printerProfilesUpdate(identifier):
trigger_event=True,
)
except InvalidProfileError:
- return make_response("Profile is invalid", 400)
+ abort(400, description="profile is invalid")
except CouldNotOverwriteError:
- return make_response(
- "Profile already exists and overwriting was not allowed", 400
- )
+ abort(400, description="Profile already exists and overwriting was not allowed")
except Exception as e:
- return make_response("Could not save profile: %s" % str(e), 500)
+ abort(500, description="Could not save profile: %s" % str(e))
else:
return jsonify({"profile": _convert_profile(saved_profile)})
diff --git a/src/octoprint/server/api/settings.py b/src/octoprint/server/api/settings.py
index 4eec18740..705f8f8ee 100644
--- a/src/octoprint/server/api/settings.py
+++ b/src/octoprint/server/api/settings.py
@@ -4,9 +4,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms
import logging
-from flask import abort, jsonify, make_response, request
+from flask import abort, jsonify, request
from flask_login import current_user
-from werkzeug.exceptions import BadRequest
import octoprint.plugin
import octoprint.util
@@ -148,7 +147,10 @@ def getSettings():
"g90InfluencesExtruder": s.getBoolean(["feature", "g90InfluencesExtruder"]),
"autoUppercaseBlacklist": s.get(["feature", "autoUppercaseBlacklist"]),
},
- "gcodeAnalysis": {"runAt": s.get(["gcodeAnalysis", "runAt"])},
+ "gcodeAnalysis": {
+ "runAt": s.get(["gcodeAnalysis", "runAt"]),
+ "bedZ": s.getFloat(["gcodeAnalysis", "bedZ"]),
+ },
"serial": {
"port": connectionOptions["portPreference"],
"baudrate": connectionOptions["baudratePreference"],
@@ -365,22 +367,11 @@ def _get_plugin_settings():
@Permissions.SETTINGS.require(403)
def setSettings():
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content-type JSON", 400)
+ abort(400, description="Expected content-type JSON")
- try:
- data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
-
- if data is None:
- return make_response("Malformed JSON body in request", 400)
-
- if not isinstance(data, dict):
- return make_response(
- "Malformed request, need settings dictionary, "
- "got a {} instead: {!r}".format(type(data).__name__, data),
- 400,
- )
+ data = request.get_json()
+ if data is None or not isinstance(data, dict):
+ abort(400, description="Malformed JSON body in request")
response = _saveSettings(data)
if response:
@@ -460,7 +451,7 @@ def _saveSettings(data):
s.setBaseFolder(folder, future[folder])
except Exception:
- return make_response("At least one of the configured folders is invalid", 400)
+ abort(400, description="At least one of the configured folders is invalid")
if "api" in data:
if "allowCrossOrigin" in data["api"]:
@@ -593,6 +584,8 @@ def _saveSettings(data):
if "gcodeAnalysis" in data:
if "runAt" in data["gcodeAnalysis"]:
s.set(["gcodeAnalysis", "runAt"], data["gcodeAnalysis"]["runAt"])
+ if "bedZ" in data["gcodeAnalysis"]:
+ s.setBoolean(["gcodeAnalysis", "bedZ"], data["gcodeAnalysis"]["bedZ"])
if "serial" in data:
if "autoconnect" in data["serial"]:
diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py
index 12be70275..f2dd80b42 100644
--- a/src/octoprint/server/api/slicing.py
+++ b/src/octoprint/server/api/slicing.py
@@ -2,8 +2,7 @@ __author__ = "Gina Hรคuรge "
__license__ = "GNU Affero General Public License http://www.gnu.org/licenses/agpl.html"
__copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms of the AGPLv3 License"
-from flask import jsonify, make_response, request, url_for
-from werkzeug.exceptions import BadRequest
+from flask import abort, jsonify, make_response, request, url_for
from octoprint.access.permissions import Permissions
from octoprint.server import slicingManager
@@ -138,7 +137,7 @@ def slicingListSlicerProfiles(slicer):
try:
return jsonify(_getSlicingProfilesData(slicer, require_configured=configured))
except (UnknownSlicer, SlicerNotConfigured):
- return make_response("Unknown slicer {slicer}".format(**locals()), 404)
+ abort(404)
@api.route("/slicing//profiles/", methods=["GET"])
@@ -148,9 +147,9 @@ def slicingGetSlicerProfile(slicer, name):
try:
profile = slicingManager.load_profile(slicer, name, require_configured=False)
except UnknownSlicer:
- return make_response("Unknown slicer {slicer}".format(**locals()), 404)
+ abort(404)
except UnknownProfile:
- return make_response("Profile not found", 404)
+ abort(404)
result = _getSlicingProfileData(slicer, name, profile)
result["data"] = profile.data
@@ -162,15 +161,11 @@ def slicingGetSlicerProfile(slicer, name):
@Permissions.SETTINGS.require(403)
def slicingAddSlicerProfile(slicer, name):
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content-type JSON", 400)
-
- try:
- json_data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Expected content-type JSON")
+ json_data = request.get_json()
if json_data is None:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Malformed JSON body in request")
data = {}
display_name = None
@@ -192,7 +187,7 @@ def slicingAddSlicerProfile(slicer, name):
description=description,
)
except UnknownSlicer:
- return make_response("Unknown slicer {slicer}".format(**locals()), 404)
+ abort(404, description="Unknown slicer")
result = _getSlicingProfileData(slicer, name, profile)
r = make_response(jsonify(result), 201)
@@ -205,24 +200,18 @@ def slicingAddSlicerProfile(slicer, name):
@Permissions.SETTINGS.require(403)
def slicingPatchSlicerProfile(slicer, name):
if "application/json" not in request.headers["Content-Type"]:
- return make_response("Expected content-type JSON", 400)
+ abort(400, description="Expected content-type JSON")
try:
profile = slicingManager.load_profile(slicer, name, require_configured=False)
except UnknownSlicer:
- return make_response("Unknown slicer {slicer}".format(**locals()), 404)
+ return abort(404)
except UnknownProfile:
- return make_response(
- "Profile {name} for slicer {slicer} not found".format(**locals()), 404
- )
-
- try:
- json_data = request.get_json()
- except BadRequest:
- return make_response("Malformed JSON body in request", 400)
+ return abort(404)
+ json_data = request.get_json()
if json_data is None:
- return make_response("Malformed JSON body in request", 400)
+ abort(400, description="Malformed JSON body in request")
data = {}
display_name = None
@@ -259,13 +248,13 @@ def slicingDelSlicerProfile(slicer, name):
try:
slicingManager.delete_profile(slicer, name)
except UnknownSlicer:
- return make_response("Unknown slicer {slicer}".format(**locals()), 404)
+ abort(404)
except CouldNotDeleteProfile as e:
- return make_response(
- "Could not delete profile {profile} for slicer {slicer}: {cause}".format(
- profile=name, slicer=slicer, cause=str(e.cause)
- ),
+ abort(
500,
+ description="Could not delete profile for slicer: {cause}".format(
+ cause=str(e.cause)
+ ),
)
return NO_CONTENT
diff --git a/src/octoprint/server/api/system.py b/src/octoprint/server/api/system.py
index b31a58ae0..6e6b52eb3 100644
--- a/src/octoprint/server/api/system.py
+++ b/src/octoprint/server/api/system.py
@@ -7,7 +7,7 @@ import threading
import psutil
import sarge
-from flask import jsonify, make_response, request, url_for
+from flask import abort, jsonify, request, url_for
from flask_babel import gettext
from octoprint.access.permissions import Permissions
@@ -84,7 +84,7 @@ def performSystemAction():
data = request.values
if "action" not in data:
- return make_response("action to perform is not defined", 400)
+ abort(400, description="action is missing")
return executeSystemCommand("custom", data["action"])
@@ -108,7 +108,7 @@ def retrieveSystemCommandsForSource(source):
elif source == "custom":
specs = _get_custom_command_specs()
else:
- return make_response("Unknown system command source: {}".format(source), 404)
+ abort(404)
return jsonify(_to_client_specs(specs))
@@ -120,18 +120,15 @@ def executeSystemCommand(source, command):
logger = logging.getLogger(__name__)
if command == "divider":
- return make_response("Dividers cannot be executed", 400)
+ abort(400, description="Dividers cannot be executed")
command_spec = _get_command_spec(source, command)
if not command_spec:
- return make_response("Command {}:{} not found".format(source, command), 404)
+ abort(404)
if "command" not in command_spec:
- return make_response(
- "Command {}:{} does not define a command to execute, can't proceed".format(
- source, command
- ),
- 500,
+ abort(
+ 500, description="Command does not define a command to execute, can't proceed"
)
do_async = command_spec.get("async", False)
@@ -154,7 +151,7 @@ def executeSystemCommand(source, command):
if not do_ignore:
error = 'Command "before" for {}:{} failed: {}'.format(source, command, e)
logger.warning(error)
- return make_response(error, 500)
+ abort(500, description=error)
try:
@@ -191,13 +188,13 @@ def executeSystemCommand(source, command):
try:
execute()
except CommandFailed as exc:
- return make_response(exc.error, 500)
+ abort(500, exc.error)
except Exception as e:
if not do_ignore:
error = "Command for {}:{} failed: {}".format(source, command, e)
logger.warning(error)
- return make_response(error, 500)
+ abort(500, error)
return NO_CONTENT
diff --git a/src/octoprint/server/api/timelapse.py b/src/octoprint/server/api/timelapse.py
index 7cb21e4ba..4bd38051a 100644
--- a/src/octoprint/server/api/timelapse.py
+++ b/src/octoprint/server/api/timelapse.py
@@ -6,7 +6,7 @@ import logging
import os
import threading
-from flask import jsonify, make_response, request, url_for
+from flask import abort, jsonify, request, url_for
import octoprint.timelapse
import octoprint.util as util
@@ -179,7 +179,7 @@ def deleteTimelapse(filename):
logging.getLogger(__file__).exception(
"Error deleting timelapse file {}".format(full_path)
)
- return make_response("Unexpected error: {}".format(ex), 500)
+ abort(500, description="Unexpected error: {}".format(ex))
return getTimelapseData()
@@ -205,8 +205,8 @@ def processUnrenderedTimelapseCommand(name):
if command == "render":
if printer.is_printing() or printer.is_paused():
- return make_response(
- "Printer is currently printing, cannot render timelapse", 409
+ abort(
+ 409, description="Printer is currently printing, cannot render timelapse"
)
octoprint.timelapse.render_unrendered_timelapse(name)
@@ -228,68 +228,56 @@ def setTimelapseConfig():
try:
postRoll = int(data["postRoll"])
except ValueError:
- return make_response(
- "Invalid value for postRoll: %r" % data["postRoll"], 400
- )
+ abort(400, description="postRoll is invalid")
else:
if postRoll >= 0:
config["postRoll"] = postRoll
else:
- return make_response("Invalid value for postRoll: %d" % postRoll, 400)
+ abort(400, description="postRoll is invalid")
if "fps" in data:
try:
fps = int(data["fps"])
except ValueError:
- return make_response("Invalid value for fps: %r" % data["fps"], 400)
+ abort(400, description="fps is invalid")
else:
if fps > 0:
config["fps"] = fps
else:
- return make_response("Invalid value for fps: %d" % fps, 400)
+ abort(400, description="fps is invalid")
if "interval" in data:
try:
interval = int(data["interval"])
except ValueError:
- return make_response(
- "Invalid value for interval: %r" % data["interval"], 400
- )
+ abort(400, description="interval is invalid")
else:
if interval > 0:
config["options"]["interval"] = interval
else:
- return make_response("Invalid value for interval: %d" % interval, 400)
+ abort(400, description="interval is invalid")
if "retractionZHop" in data:
try:
retractionZHop = float(data["retractionZHop"])
except ValueError:
- return make_response(
- "Invalid value for retraction Z-Hop: %r" % data["retractionZHop"], 400
- )
+ abort(400, description="retractionZHop is invalid")
else:
if retractionZHop >= 0:
config["options"]["retractionZHop"] = retractionZHop
else:
- return make_response(
- "Invalid value for retraction Z-Hop: %f" % retractionZHop, 400
- )
+ abort(400, description="retractionZHop is invalid")
if "minDelay" in data:
try:
minDelay = float(data["minDelay"])
except ValueError:
- return make_response(
- "Invalid value for minimum delay: %r" % data["minDelay"], 400
- )
+ abort(400, description="minDelay is invalid")
else:
if minDelay > 0:
config["options"]["minDelay"] = minDelay
else:
- return make_response(
- "Invalid value for minimum delay: %f" % minDelay, 400
- )
+ abort(400, description="minDelay is invalid")
if (
admin_permission.can()
diff --git a/src/octoprint/server/util/__init__.py b/src/octoprint/server/util/__init__.py
index b7bc9537e..2bffcb591 100644
--- a/src/octoprint/server/util/__init__.py
+++ b/src/octoprint/server/util/__init__.py
@@ -44,7 +44,7 @@ def loginFromApiKeyRequestHandler():
if loginUserFromApiKey():
_flask.g.login_via_apikey = True
except InvalidApiKeyException:
- return _flask.make_response("Invalid API key", 403)
+ _flask.abort(403)
def loginFromAuthorizationHeaderRequestHandler():
@@ -55,7 +55,7 @@ def loginFromAuthorizationHeaderRequestHandler():
if loginUserFromAuthorizationHeader():
_flask.g.login_via_header = True
except InvalidApiKeyException:
- return _flask.make_response("Invalid API key", 403)
+ _flask.abort(403)
class InvalidApiKeyException(Exception):
@@ -117,7 +117,7 @@ def requireLoginRequestHandler():
user = flask_login.current_user
if user is None or user.is_anonymous or not user.is_active:
- return flask.make_response("Forbidden", 403)
+ _flask.abort(403)
def corsRequestHandler():
diff --git a/src/octoprint/server/util/flask.py b/src/octoprint/server/util/flask.py
index 7064f7a9a..ffa3b956d 100644
--- a/src/octoprint/server/util/flask.py
+++ b/src/octoprint/server/util/flask.py
@@ -1297,11 +1297,13 @@ def with_revalidation_checking(
def decorator(f):
@functools.wraps(f)
def decorated_function(*args, **kwargs):
+ from octoprint.server import NOT_MODIFIED
+
lm = lastmodified_factory()
etag = etag_factory(lm)
if condition(lm, etag) and not unless():
- return make_response("Not Modified", 304)
+ return NOT_MODIFIED
# generate response
response = f(*args, **kwargs)
@@ -1539,7 +1541,7 @@ def no_firstrun_access(func):
octoprint.server.userManager is None
or not octoprint.server.userManager.has_been_customized()
):
- return flask.make_response("OctoPrint isn't setup yet", 403)
+ flask.abort(403)
return func(*args, **kwargs)
return decorated_view
@@ -1561,9 +1563,7 @@ def firstrun_only_access(func):
):
return func(*args, **kwargs)
else:
- return flask.make_response(
- "OctoPrint is already setup, this resource is not longer available.", 403
- )
+ flask.abort(403)
return decorated_view
@@ -1578,34 +1578,56 @@ def get_remote_address(request):
def get_json_command_from_request(request, valid_commands):
content_type = request.headers.get("Content-Type", None)
if content_type is None or "application/json" not in content_type:
- return None, None, make_response("Expected content-type JSON", 400)
+ flask.abort(400, description="Expected content-type JSON")
data = request.get_json()
if data is None:
- return (
- None,
- None,
- make_response("Malformed JSON body or wrong content-type in request", 400),
+ flask.abort(
+ 400, description="Malformed JSON body or wrong content-type in request"
)
if "command" not in data or data["command"] not in valid_commands:
- return None, None, make_response("Expected valid command", 400)
+ flask.abort(400, description="command is invalid")
command = data["command"]
- for parameter in valid_commands[command]:
- if parameter not in data:
- return (
- None,
- None,
- make_response(
- "Mandatory parameter %s missing for command %s"
- % (parameter, command),
- 400,
- ),
- )
+ if any(map(lambda x: x not in data, valid_commands[command])):
+ flask.abort(400, description="Mandatory parameters missing")
return command, data, None
+def 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".
+
+ Args:
+ message: The message in the response body
+ status: The HTTP status code
+
+ Returns:
+
+ """
+ return make_response(message, status, {"Content-Type": "text/plain"})
+
+
+def 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"}``.
+
+ Args:
+ message: The error message to put into the response
+ status: The HTTP status code
+
+ Returns: a flask response to return to the client
+ """
+ return make_response(flask.jsonify(error=message), status)
+
+
##~~ Flask-Assets resolver with plugin asset support
diff --git a/src/octoprint/server/util/tornado.py b/src/octoprint/server/util/tornado.py
index 2c3c686e0..37e082677 100644
--- a/src/octoprint/server/util/tornado.py
+++ b/src/octoprint/server/util/tornado.py
@@ -1181,9 +1181,13 @@ class LargeResponseHandler(
def compute_etag(self):
if self._etag_generator is not None:
- return self._etag_generator(self)
+ etag = self._etag_generator(self)
else:
- return self.get_content_version(self.absolute_path)
+ etag = str(self.get_content_version(self.absolute_path))
+
+ if not etag.endswith('"'):
+ etag = '"{}"'.format(etag)
+ return etag
# noinspection PyAttributeOutsideInit
def get_content_type(self):
@@ -1326,7 +1330,7 @@ class UrlProxyHandler(
if not extension:
return None
- return "%s%s" % (self._basename, extension)
+ return "{}{}".format(self._basename, extension)
class StaticDataHandler(
diff --git a/src/octoprint/settings.py b/src/octoprint/settings.py
index 11aa2b8d8..92d6a4b74 100644
--- a/src/octoprint/settings.py
+++ b/src/octoprint/settings.py
@@ -245,6 +245,7 @@ default_settings = {
"throttle_highprio": 0.0,
"throttle_lines": 100,
"runAt": "idle", # 'never', 'idle', 'always'
+ "bedZ": 0.0,
},
"feature": {
"temperatureGraph": True,
diff --git a/src/octoprint/static/js/app/viewmodels/settings.js b/src/octoprint/static/js/app/viewmodels/settings.js
index ac9222ce1..ae8074a10 100644
--- a/src/octoprint/static/js/app/viewmodels/settings.js
+++ b/src/octoprint/static/js/app/viewmodels/settings.js
@@ -770,7 +770,7 @@ $(function () {
$(".reload_nonconflicts", self.settingsUpdatedDialog).click(function (e) {
e.preventDefault();
self.settingsUpdatedDialog.modal("hide");
- self.requestData(undefined, true);
+ self.requestData(true);
return false;
});
@@ -839,14 +839,14 @@ $(function () {
self.requestData = function (local) {
// handle old parameter format
var callback = undefined;
- if (arguments.length == 2 || _.isFunction(local)) {
+ if (arguments.length === 2 || _.isFunction(local)) {
var exc = new Error();
log.warn(
"The callback parameter of SettingsViewModel.requestData is deprecated, the method now returns a promise, please use that instead. Stacktrace:",
exc.stack || exc.stacktrace || ""
);
- if (arguments.length == 2) {
+ if (arguments.length === 2) {
callback = arguments[0];
local = arguments[1];
} else {
diff --git a/src/octoprint/util/__init__.py b/src/octoprint/util/__init__.py
index 2a1ae31c7..3ef281f2c 100644
--- a/src/octoprint/util/__init__.py
+++ b/src/octoprint/util/__init__.py
@@ -334,9 +334,9 @@ def get_formatted_size(num):
for x in ["B", "KB", "MB", "GB"]:
if num < 1024:
- return "%3.1f%s" % (num, x)
+ return "{:3.1f}{}".format(num, x)
num /= 1024
- return "%3.1f%s" % (num, "TB")
+ return "{:3.1f}{}".format(num, "TB")
def is_allowed_file(filename, extensions):
@@ -1115,7 +1115,7 @@ class DefaultOrderedDict(collections.OrderedDict):
# noinspection PyMethodOverriding
def __repr__(self):
- return "OrderedDefaultDict(%s, %s)" % (
+ return "OrderedDefaultDict({}, {})".format(
self.default_factory,
collections.OrderedDict.__repr__(self),
)
diff --git a/src/octoprint/util/gcodeInterpreter.py b/src/octoprint/util/gcodeInterpreter.py
index 33ec56344..fccdc25e9 100644
--- a/src/octoprint/util/gcodeInterpreter.py
+++ b/src/octoprint/util/gcodeInterpreter.py
@@ -143,11 +143,33 @@ class MinMax3D:
>>> empty = MinMax3D()
>>> empty.size == Vector3D(0.0, 0.0, 0.0)
True
+ >>> weird = MinMax3D(min_z=-1.0)
+ >>> weird.record(Vector3D(2.0, 2.0, 2.0))
+ >>> weird.record(Vector3D(1.0, 2.0, 3.0))
+ >>> weird.min.z == -1.0
+ True
+ >>> weird.size == Vector3D(1.0, 0.0, 4.0)
+ True
"""
- def __init__(self):
- self.min = Vector3D(float("inf"), float("inf"), float("inf"))
- self.max = Vector3D(-float("inf"), -float("inf"), -float("inf"))
+ def __init__(
+ self,
+ min_x=None,
+ min_y=None,
+ min_z=None,
+ max_x=None,
+ max_y=None,
+ max_z=None,
+ ):
+ min_x = min_x if min_x is not None else float("inf")
+ min_y = min_y if min_y is not None else float("inf")
+ min_z = min_z if min_z is not None else float("inf")
+ max_x = max_x if max_x is not None else -float("inf")
+ max_y = max_y if max_y is not None else -float("inf")
+ max_z = max_z if max_z is not None else -float("inf")
+
+ self.min = Vector3D(min_x, min_y, min_z)
+ self.max = Vector3D(max_x, max_y, max_z)
def record(self, coordinate):
"""
@@ -224,7 +246,9 @@ class gcode:
offsets=None,
max_extruders=10,
g90_extruder=False,
+ bed_z=0.0,
):
+ self._minMax.min.z = bed_z
if os.path.isfile(filename):
self.filename = filename
self._fileSize = os.stat(filename).st_size
@@ -445,17 +469,17 @@ class gcode:
x = getCodeFloat(line, "X")
y = getCodeFloat(line, "Y")
z = getCodeFloat(line, "Z")
- center = Vector3D(0.0, 0.0, 0.0)
+ origin = Vector3D(0.0, 0.0, 0.0)
if x is None and y is None and z is None:
- pos = center
+ pos = origin
else:
pos = Vector3D(pos)
if x is not None:
- pos.x = center.x
+ pos.x = origin.x
if y is not None:
- pos.y = center.y
+ pos.y = origin.y
if z is not None:
- pos.z = center.z
+ pos.z = origin.z
elif gcode == "G90": # Absolute position
relativeMode = False
if g90_extruder:
diff --git a/tests/cypress/util/util.js b/tests/cypress/util/util.js
index 614dd6263..346b5a6dd 100644
--- a/tests/cypress/util/util.js
+++ b/tests/cypress/util/util.js
@@ -5,7 +5,7 @@ export const prepare_server = () => {
cy.route("GET", "/api/settings").as("settings");
cy.route("GET", "/api/files?recursive=true").as("files");
cy.route("GET", "/plugin/softwareupdate/check").as("softwareupdate");
- cy.route("GET", "/api/plugin/pluginmanager").as("pluginmanager");
+ cy.route("GET", "/plugin/pluginmanager/plugins").as("pluginmanager");
cy.route("POST", "/api/connection").as("connectionCommand");
cy.route("GET", "/api/connection").as("connectionDetails");
};
diff --git a/versioneer.py b/versioneer.py
index 7c2305223..a2888abc5 100644
--- a/versioneer.py
+++ b/versioneer.py
@@ -501,7 +501,7 @@ def run_command(commands, args, cwd=None, verbose=False, hide_stderr=False):
return None
else:
if verbose:
- print("unable to find command, tried %s" % (commands,))
+ print("unable to find command, tried {}".format(commands))
return None
stdout = p.communicate()[0].strip()
if sys.version_info[0] >= 3:
@@ -650,11 +650,11 @@ def git_get_keywords(versionfile_abs):
f = io.open(versionfile_abs, "rt", encoding="utf-8")
for line in f.readlines():
if line.strip().startswith("git_refnames ="):
- mo = re.search(r'=\s*"(.*)"', line)
+ mo = re.search(r'=\\s*"(.*)"', line)
if mo:
keywords["refnames"] = mo.group(1)
if line.strip().startswith("git_full ="):
- mo = re.search(r'=\s*"(.*)"', line)
+ mo = re.search(r'=\\s*"(.*)"', line)
if mo:
keywords["full"] = mo.group(1)
f.close()
@@ -686,7 +686,7 @@ def git_versions_from_keywords(keywords, tag_prefix, verbose):
# between branches and tags. By ignoring refnames without digits, we
# filter out many common branch names like "release" and
# "stabilization", as well as "HEAD" and "master".
- tags = set(r for r in refs if re.search(r'\d', r))
+ tags = set(r for r in refs if re.search(r'\\d', r))
if verbose:
print("discarding '%%s', no digits" %% ",".join(refs-tags))
@@ -778,7 +778,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if "-" in git_describe:
# TAG-NUM-gHEX
- mo = re.search(r'^(.+)-(\d+)-g([0-9a-f]+)$', git_describe)
+ mo = re.search(r'^(.+)-(\\d+)-g([0-9a-f]+)$', git_describe)
if not mo:
# unparseable. Maybe git-describe is misbehaving?
pieces["error"] = ("unable to parse git-describe output: '%%s'"
@@ -1379,7 +1379,7 @@ def git_pieces_from_vcs(tag_prefix, root, verbose, run_command=run_command):
if verbose:
fmt = "tag '%s' doesn't start with prefix '%s'"
print(fmt % (full_tag, tag_prefix))
- pieces["error"] = "tag '%s' doesn't start with prefix '%s'" % (
+ pieces["error"] = "tag '{}' doesn't start with prefix '{}'".format(
full_tag,
tag_prefix,
)
@@ -1609,7 +1609,7 @@ def write_to_version_file(filename, versions):
with io.open(filename, "wt", encoding="utf-8") as f:
f.write(SHORT_VERSION_PY % contents)
- print("set %s to '%s'" % (filename, versions["version"]))
+ print("set {} to '{}'".format(filename, versions["version"]))
def plus_or_dot(pieces):
@@ -1884,7 +1884,7 @@ def get_versions(verbose=False):
try:
ver = versions_from_file(versionfile_abs)
if verbose:
- print("got version from file %s %s" % (versionfile_abs, ver))
+ print("got version from file {} {}".format(versionfile_abs, ver))
return ver
except NotThisMethod:
pass