diff --git a/src/octoprint/plugin/types.py b/src/octoprint/plugin/types.py index c724b9c35..b3db80d55 100644 --- a/src/octoprint/plugin/types.py +++ b/src/octoprint/plugin/types.py @@ -1279,7 +1279,7 @@ class SimpleApiPlugin(OctoPrintPlugin): If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` for you. You may also return regular responses as you would return from any Flask view here though, e.g. - ``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``. + ``return flask.jsonify(result="some json result")`` or ``flask.abort(404)``. :param string command: the command with which the resource was called :param dict data: the full request body of the POST request parsed from JSON into a Python dictionary @@ -1297,7 +1297,7 @@ class SimpleApiPlugin(OctoPrintPlugin): If your plugin returns nothing here, OctoPrint will return an empty response with return code ``204 No content`` for you. You may also return regular responses as you would return from any Flask view here though, e.g. - ``return flask.jsonify(result="some json result")`` or ``return flask.make_response("Not found", 404)``. + ``return flask.jsonify(result="some json result")`` or ``flask.abort(404)``. :param request: the Flask request object :return: ``None`` in which case OctoPrint will generate a ``204 No content`` response with empty body, or optionally @@ -1327,7 +1327,7 @@ class BlueprintPlugin(OctoPrintPlugin, RestartNeedingPlugin): @octoprint.plugin.BlueprintPlugin.route("/echo", methods=["GET"]) def myEcho(self): if not "text" in flask.request.values: - return flask.make_response("Expected a text to echo back.", 400) + abort(400, description="Expected a text to echo back.") return flask.request.values["text"] __plugin_implementation__ = MyBlueprintPlugin() diff --git a/src/octoprint/plugins/action_command_notification/__init__.py b/src/octoprint/plugins/action_command_notification/__init__.py index e58007004..1df93cec8 100644 --- a/src/octoprint/plugins/action_command_notification/__init__.py +++ b/src/octoprint/plugins/action_command_notification/__init__.py @@ -69,7 +69,7 @@ class ActionCommandNotificationPlugin( def on_api_get(self, request): if not Permissions.PLUGIN_ACTION_COMMAND_NOTIFICATION_SHOW.can(): - return flask.abort(403, "Insufficient permissions") + return flask.abort(403) return flask.jsonify( notifications=[ {"timestamp": notification[0], "message": notification[1]} diff --git a/src/octoprint/plugins/action_command_prompt/__init__.py b/src/octoprint/plugins/action_command_prompt/__init__.py index e9cd2e4bb..9a53bc10d 100644 --- a/src/octoprint/plugins/action_command_prompt/__init__.py +++ b/src/octoprint/plugins/action_command_prompt/__init__.py @@ -126,10 +126,10 @@ class ActionCommandPromptPlugin( def on_api_command(self, command, data): if command == "select": if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): - return flask.abort(403, "Insufficient permissions") + return flask.abort(403) if self._prompt is None: - return flask.abort(409, "No active prompt") + return flask.abort(409, description="No active prompt") choice = data["choice"] if not isinstance(choice, int) or not self._prompt.validate_choice(choice): @@ -141,7 +141,7 @@ class ActionCommandPromptPlugin( def on_api_get(self, request): if not Permissions.PLUGIN_ACTION_COMMAND_PROMPT_INTERACT.can(): - return flask.abort(403, "Insufficient permissions") + return flask.abort(403) if self._prompt is None: return flask.jsonify() else: diff --git a/src/octoprint/plugins/announcements/__init__.py b/src/octoprint/plugins/announcements/__init__.py index 7c320d4b8..86465af02 100644 --- a/src/octoprint/plugins/announcements/__init__.py +++ b/src/octoprint/plugins/announcements/__init__.py @@ -289,7 +289,7 @@ class AnnouncementPlugin( elif command == "toggle": if not Permissions.PLUGIN_ANNOUNCEMENTS_MANAGE.can(): - return flask.make_response("Insufficient rights", 403) + flask.abort(403) self._toggle(channel) return NO_CONTENT diff --git a/src/octoprint/plugins/appkeys/__init__.py b/src/octoprint/plugins/appkeys/__init__.py index 855ac50b5..326b95f18 100644 --- a/src/octoprint/plugins/appkeys/__init__.py +++ b/src/octoprint/plugins/appkeys/__init__.py @@ -157,10 +157,10 @@ class AppKeysPlugin( def handle_request(self): data = flask.request.json if data is None: - return flask.make_response("Missing key request", 400) + flask.abort(400, description="Missing key request") if "app" not in data: - return flask.make_response("No app name provided", 400) + flask.abort(400, description="No app name provided") app_name = data["app"] user_id = None @@ -208,7 +208,7 @@ class AppKeysPlugin( def handle_decision(self, user_token): data = flask.request.json if "decision" not in data: - return flask.make_response("No decision provided", 400) + flask.abort(400, description="No decision provided") decision = data["decision"] in valid_boolean_trues user_id = current_user.get_name() diff --git a/src/octoprint/plugins/backup/__init__.py b/src/octoprint/plugins/backup/__init__.py index 9e204d223..3094a8688 100644 --- a/src/octoprint/plugins/backup/__init__.py +++ b/src/octoprint/plugins/backup/__init__.py @@ -203,12 +203,13 @@ class BackupPlugin( if not Permissions.PLUGIN_BACKUP_ACCESS.can() and not self._settings.global_get( ["server", "firstRun"] ): - return flask.abort(403) + flask.abort(403) if not self._restore_supported(self._settings): - return flask.make_response( - "Invalid request, the restores are not supported on the underlying operating system", + flask.abort( 400, + description="Invalid request, the restores are not " + "supported on the underlying operating system", ) input_name = "file" @@ -236,9 +237,10 @@ class BackupPlugin( return flask.abort(404) else: - return flask.make_response( - "Invalid request, neither a file nor a path of a file to restore provided", + flask.abort( 400, + description="Invalid request, neither a file nor a path of a file to " + "restore provided", ) def on_install_plugins(plugins): diff --git a/src/octoprint/plugins/logging/__init__.py b/src/octoprint/plugins/logging/__init__.py index 6ef2e0c1f..3e8728ca4 100644 --- a/src/octoprint/plugins/logging/__init__.py +++ b/src/octoprint/plugins/logging/__init__.py @@ -8,7 +8,7 @@ import io import os import yaml -from flask import jsonify, make_response, request, url_for +from flask import abort, jsonify, request, url_for from flask_babel import gettext from werkzeug.exceptions import BadRequest from werkzeug.utils import secure_filename @@ -94,7 +94,7 @@ class LoggingPlugin( or is_hidden_path(secure) or not filename.endswith(".log") ): - return make_response("File not found", 404) + abort(404) os.remove(secure) @@ -119,15 +119,15 @@ class LoggingPlugin( @Permissions.PLUGIN_LOGGING_MANAGE.require(403) def set_logging_levels_api(self): 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.json except BadRequest: - return make_response("Malformed JSON body in request", 400) + abort(400, description="Malformed JSON body in request") if not isinstance(json_data, dict): - return make_response("Invalid log level configuration", 400) + abort(400, description="Invalid log level configuration") # TODO validate further diff --git a/src/octoprint/plugins/pluginmanager/__init__.py b/src/octoprint/plugins/pluginmanager/__init__.py index 7a8ec960b..9a6ad46a4 100644 --- a/src/octoprint/plugins/pluginmanager/__init__.py +++ b/src/octoprint/plugins/pluginmanager/__init__.py @@ -21,7 +21,7 @@ import filetype import pkg_resources import requests import sarge -from flask import Response, abort, jsonify, make_response, request +from flask import Response, abort, jsonify, request from flask_babel import gettext from past.builtins import basestring @@ -367,7 +367,7 @@ class PluginManagerPlugin( input_upload_path not in flask.request.values or input_upload_name not in flask.request.values ): - return flask.make_response("No file included", 400) + abort(400, description="No file included") upload_path = flask.request.values[input_upload_path] upload_name = flask.request.values[input_upload_name] @@ -378,9 +378,9 @@ class PluginManagerPlugin( ) ) if not len(exts): - return flask.make_response( - "File doesn't have a valid extension for a plugin archive or a single file plugin", + abort( 400, + description="File doesn't have a valid extension for a plugin archive or a single file plugin", ) ext = exts[0] @@ -407,7 +407,7 @@ class PluginManagerPlugin( with self._install_lock: if self._install_task is not None: - return make_response("There's already a plugin being installed", 409) + abort(409, description="There's already a plugin being installed") self._install_task = threading.Thread( target=perform_install, @@ -506,7 +506,7 @@ class PluginManagerPlugin( @Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403) def retrieve_plugin_orphans(self): if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) + abort(403) refresh = request.values.get("refresh", "false") in valid_boolean_trues if refresh: @@ -549,7 +549,7 @@ class PluginManagerPlugin( @Permissions.PLUGIN_PLUGINMANAGER_MANAGE.require(403) def retrieve_plugin_repository(self): if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) + abort(403) refresh = request.values.get("refresh", "false") in valid_boolean_trues if refresh or not self._is_repository_cache_valid(): @@ -612,21 +612,21 @@ class PluginManagerPlugin( def on_api_command(self, command, data): if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) + abort(403) if self._printer.is_printing() or self._printer.is_paused(): # do not update while a print job is running - return make_response("Printer is currently printing or paused", 409) + abort(409, description="Printer is currently printing or paused") if command == "install": if not Permissions.PLUGIN_PLUGINMANAGER_INSTALL.can(): - return make_response("Insufficient rights", 403) + abort(403) url = data["url"] plugin_name = data["plugin"] if "plugin" in data else None with self._install_lock: if self._install_task is not None: - return make_response("There's already a plugin being installed", 409) + abort(409, description="There's already a plugin being installed") self._install_task = threading.Thread( target=self.command_install, @@ -646,7 +646,7 @@ class PluginManagerPlugin( elif command == "uninstall": plugin_name = data["plugin"] if plugin_name not in self._plugin_manager.plugins: - return make_response("Unknown plugin", 404) + abort(404, description="Unknown plugin") plugin = self._plugin_manager.plugins[plugin_name] return self.command_uninstall(plugin, cleanup=data.get("cleanup", False)) @@ -667,7 +667,7 @@ class PluginManagerPlugin( elif command == "enable" or command == "disable": plugin_name = data["plugin"] if plugin_name not in self._plugin_manager.plugins: - return make_response("Unknown plugin", 404) + abort(404, description="Unknown plugin") plugin = self._plugin_manager.plugins[plugin_name] return self.command_toggle(plugin, command) @@ -679,7 +679,7 @@ class PluginManagerPlugin( ) def on_api_get(self, r): if not Permissions.PLUGIN_PLUGINMANAGER_MANAGE.can(): - return make_response("Insufficient rights", 403) + abort(403) refresh_repository = ( request.values.get("refresh_repository", "false") in valid_boolean_trues @@ -1192,15 +1192,15 @@ class PluginManagerPlugin( def command_uninstall(self, plugin, cleanup=False): if plugin.key == "pluginmanager": - return make_response("Can't uninstall Plugin Manager", 403) + abort(403, description="Can't uninstall Plugin Manager") if not plugin.managable: - return make_response( - "Plugin is not managable and hence cannot be uninstalled", 403 + abort( + 403, description="Plugin is not managable and hence cannot be uninstalled" ) if plugin.bundled: - return make_response("Bundled plugins cannot be uninstalled", 403) + abort(403, description="Bundled plugins cannot be uninstalled") if plugin.origin is None: self._logger.warning( @@ -1208,7 +1208,7 @@ class PluginManagerPlugin( **locals() ) ) - return make_response("Could not uninstall plugin, its origin is unknown") + abort(500, description="Could not uninstall plugin, its origin is unknown") if plugin.origin.type == "entry_point": # plugin is installed through entry point, need to use pip to uninstall it @@ -1221,9 +1221,9 @@ class PluginManagerPlugin( self._call_pip(pip_args) except Exception: self._logger.exception("Could not uninstall plugin via pip") - return make_response( - "Could not uninstall plugin via pip, see the log for more details", + abort( 500, + description="Could not uninstall plugin via pip, see the log for more details", ) elif plugin.origin.type == "folder": @@ -1258,7 +1258,7 @@ class PluginManagerPlugin( **locals() ) ) - return make_response("Could not uninstall plugin, its origin is unknown") + abort(500, description="Could not uninstall plugin, its origin is unknown") needs_restart = self._plugin_manager.is_restart_needing_plugin(plugin) or cleanup needs_refresh = plugin.implementation and isinstance( @@ -1446,7 +1446,7 @@ class PluginManagerPlugin( def command_toggle(self, plugin, command): if plugin.key == "pluginmanager" or (plugin.hidden and plugin.bundled): - return make_response("Can't enable/disable Plugin Manager", 400) + abort(400, description="Can't enable/disable Plugin Manager") pending = (command == "disable" and plugin.key in self._pending_enable) or ( command == "enable" and plugin.key in self._pending_disable diff --git a/src/octoprint/plugins/softwareupdate/__init__.py b/src/octoprint/plugins/softwareupdate/__init__.py index 798ffa6c7..550cefcdd 100644 --- a/src/octoprint/plugins/softwareupdate/__init__.py +++ b/src/octoprint/plugins/softwareupdate/__init__.py @@ -1017,8 +1017,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(): @@ -1083,30 +1086,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( @@ -1129,7 +1133,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() diff --git a/src/octoprint/server/__init__.py b/src/octoprint/server/__init__.py index 78e6a1d3a..28e06a9e7 100644 --- a/src/octoprint/server/__init__.py +++ b/src/octoprint/server/__init__.py @@ -42,6 +42,7 @@ from flask_login import ( # noqa: F401 from past.builtins import basestring, unicode from watchdog.observers import Observer from watchdog.observers.polling import PollingObserver +from werkzeug.exceptions import HTTPException import octoprint.util import octoprint.util.net @@ -65,8 +66,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") @@ -1733,9 +1734,11 @@ class Server(object): # 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()) @@ -1750,6 +1753,13 @@ class Server(object): 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() diff --git a/src/octoprint/server/api/__init__.py b/src/octoprint/server/api/__init__.py index feea98729..056d68283 100644 --- a/src/octoprint/server/api/__init__.py +++ b/src/octoprint/server/api/__init__.py @@ -10,6 +10,7 @@ import logging from flask import ( Blueprint, + Response, abort, current_app, g, @@ -80,22 +81,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, can't proceed", - 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: @@ -118,22 +137,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, can't proceed", - 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: @@ -249,14 +265,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(): @@ -298,7 +306,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 @@ -335,12 +343,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"]) @@ -584,10 +592,7 @@ def _test_url(data): try: timeout = float(data["timeout"]) except Exception: - return make_response( - "Not a valid value for timeout (must be int or float)", - 400, - ) + abort(400, description="timeout is invalid") if "validSsl" in data: valid_ssl = data["validSsl"] in valid_boolean_trues @@ -611,13 +616,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"]) ) @@ -698,24 +703,18 @@ def _test_server(data): try: port = int(data["port"]) except Exception: - return make_response("Not a valid value for port (must be int)", 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( - "Not a valid value for timeout (must be int or float)", - 400, - ) + abort(400, description="Invalid value for timeout") protocol = data.get("protocol", "tcp") if protocol not in ("tcp", "udp"): - return make_response( - "Not a valid value for protocol, must be tcp or udp", - 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 4ddc9bdc1..f024dc6eb 100644 --- a/src/octoprint/server/api/access.py +++ b/src/octoprint/server/api/access.py @@ -5,9 +5,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 @@ -39,19 +38,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"] @@ -90,12 +86,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 = {} @@ -149,22 +142,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"] @@ -207,12 +196,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: @@ -224,9 +213,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( @@ -261,27 +247,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", 404, [])) + abort(404) return jsonify(SUCCESS) else: - return make_response(("Forbidden", 403, [])) + abort(403) @api.route("/access/users//settings", methods=["GET"]) @@ -295,12 +278,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", 404) + abort(404) @api.route("/access/users//settings", methods=["PATCH"]) @@ -314,21 +297,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", 404) + abort(404) @api.route("/access/users//apikey", methods=["DELETE"]) @@ -345,10 +325,10 @@ def delete_apikey_for_user(username): try: userManager.delete_api_key(username) except users.UnknownUser: - return make_response(("Unknown user", 404, [])) + abort(404) return jsonify(SUCCESS) else: - return make_response(("Forbidden", 403, [])) + abort(403) @api.route("/access/users//apikey", methods=["POST"]) @@ -368,10 +348,10 @@ def generate_apikey_for_user(username): try: apikey = userManager.generate_api_key(username) except users.UnknownUser: - return make_response(("Unknown user", 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 905302fcd..ba8a2d18e 100644 --- a/src/octoprint/server/api/connection.py +++ b/src/octoprint/server/api/connection.py @@ -5,7 +5,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 @@ -49,15 +49,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", 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", 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", 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 bd3301e57..10a0a6a04 100644 --- a/src/octoprint/server/api/files.py +++ b/src/octoprint/server/api/files.py @@ -11,7 +11,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 @@ -180,7 +180,7 @@ def readGcodeFiles(): ) def readGcodeFilesForOrigin(origin): if origin not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown origin", 404) + abort(404) filter = request.values.get("filter", False) recursive = request.values.get("recursive", "false") in valid_boolean_trues @@ -216,10 +216,10 @@ def readGcodeFilesForOrigin(origin): ) def readGcodeFile(target, filename): if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target", 404) + abort(404) if filename != fileManager.sanitize(target, filename): - return make_response("File not found", 404) + abort(404) recursive = False if "recursive" in request.values: @@ -227,7 +227,7 @@ def readGcodeFile(target, filename): file = _getFileDetails(target, filename, recursive=recursive) if not file: - return make_response("File not found", 404) + abort(404) return jsonify(file) @@ -453,7 +453,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", 404) + abort(404) upload = octoprint.filemanager.util.DiskFileWrapper( request.values[input_upload_name], request.values[input_upload_path] @@ -467,12 +467,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 = ( @@ -492,14 +492,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: @@ -517,7 +515,7 @@ def uploadGcodeFile(target): futureFilename = None if futureFilename is None: - return make_response("Can not upload file, wrong format?", 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" @@ -534,9 +532,9 @@ def uploadGcodeFile(target): ) if not printer.can_modify_file(futureFullPathInStorage, sd): - return make_response( - "Trying to overwrite file that is currently being printed", + abort( 409, + description="Trying to overwrite file that is currently being printed", ) reselect = printer.is_current_file(futureFullPathInStorage, sd) @@ -594,12 +592,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", - 400, - ) + abort(400, description="Could not upload file, invalid type") else: - return make_response("Could not upload the file", 500) + abort(500, description="Could not upload file") if octoprint.filemanager.valid_file_type(added_file, "stl"): filename = added_file @@ -684,13 +679,13 @@ def uploadGcodeFile(target): foldername = request.values["foldername"] if target not in [FileDestinations.LOCAL]: - return make_response("Unknown 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( @@ -699,10 +694,7 @@ def uploadGcodeFile(target): futureFullPath = fileManager.join_path(target, futurePath, futureName) if octoprint.filemanager.valid_file_type(futureName): - return make_response( - "Can't create folder, please try another name", - 409, - ) + abort(409, description="Can't create folder, please try another name") try: added_folder = fileManager.add_folder( @@ -710,9 +702,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") + abort(400, description="Could not create folder, invalid directory") else: - return make_response("Could not create folder") + abort(500, description="Could not create folder") location = url_for( ".readGcodeFile", @@ -732,17 +724,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", 404) + abort(404) if filename != fileManager.sanitize(target, filename): - return make_response("File not found", 404) + abort(404) # valid file commands, dict mapping command name to mandatory parameters valid_commands = { @@ -762,27 +754,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", 404) + abort(404) # selects/loads a file if not octoprint.filemanager.valid_file_type(filename, type="machinecode"): - return make_response( - "Cannot select file for printing, not a machinecode file", + 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 @@ -797,7 +790,7 @@ def gcodeFileCommand(filename, target): elif command == "slice": with Permissions.SLICE.require(403): if not _verifyFileExists(target, filename): - return make_response("File not found", 404) + abort(404) try: if "slicer" in data: @@ -810,12 +803,9 @@ def gcodeFileCommand(filename, target): slicer_instance = slicingManager.get_slicer("cura") else: - return make_response( - "Cannot slice file, no slicer available", - 415, - ) + abort(415, description="Cannot slice file, no slicer available") except octoprint.slicing.UnknownSlicer: - return make_response("Slicer is not available", 400) + abort(404) if not any( [ @@ -825,7 +815,7 @@ def gcodeFileCommand(filename, target): ) ] ): - return make_response("Cannot slice file, not a model file", 415) + abort(415, description="Cannot slice file, not a model file") cores = psutil.cpu_count() if ( @@ -834,9 +824,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 this slicer while printing on single core systems or systems of unknown core count due to performance reasons", + 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"]: @@ -880,9 +870,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", + abort( 409, + description="Trying to slice into file that is currently being printed", ) if "profile" in data and data["profile"]: @@ -912,17 +902,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 @@ -964,7 +955,7 @@ def gcodeFileCommand(filename, target): ), ) except octoprint.slicing.UnknownProfile: - return make_response("Profile doesn't exist", 400) + abort(404, description="Unknown profile") location = url_for( ".readGcodeFile", target=target, filename=full_path, _external=True @@ -991,7 +982,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", 404) + abort(404) printer_profile = None if "printerProfile" in data and data["printerProfile"]: @@ -1000,18 +991,18 @@ def gcodeFileCommand(filename, target): if not fileManager.analyse( target, filename, printer_profile_id=printer_profile ): - return make_response("No analysis possible", 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), 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", 404) + abort(404) path, name = fileManager.split_path(target, filename) @@ -1032,18 +1023,14 @@ def gcodeFileCommand(filename, target): if _verifyFileExists(target, destination) or _verifyFolderExists( target, destination ): - return make_response( - "File or folder does already exist", - 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( - "Neither file nor folder, can't {}", - 400, + abort( + 400, description="Neither file nor folder, can't {}".format(command) ) if command == "copy": @@ -1051,10 +1038,7 @@ def gcodeFileCommand(filename, target): if _verifyFileExists(target, destination) or _verifyFolderExists( target, destination ): - return make_response( - "File or folder does already exist", - 409, - ) + abort(409, description="File or folder does already exist") if is_file: fileManager.copy_file(target, filename, destination) @@ -1064,9 +1048,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", + abort( 409, + description="Trying to move a file or folder that is currently in use", ) # destination already there AND not ourselves (= display rename)? error... @@ -1074,10 +1058,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", - 409, - ) + abort(409, description="File or folder does already exist") # deselect the file if it's currently selected currentOrigin, currentFilename = _getCurrentFile() @@ -1119,19 +1100,19 @@ def gcodeFileCommand(filename, target): @Permissions.FILES_DELETE.require(403) def deleteGcodeFile(filename, target): if filename != fileManager.sanitize(target, filename): - return make_response("File not found", 400) + abort(404) if not _verifyFileExists(target, filename) and not _verifyFolderExists( target, filename ): - return make_response("File not found", 404) + abort(404) if target not in [FileDestinations.LOCAL, FileDestinations.SDCARD]: - return make_response("Unknown target", 404) + abort(404) if _verifyFileExists(target, filename): if _isBusy(target, filename): - return make_response("Trying to delete a file that is currently in use", 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() @@ -1150,9 +1131,9 @@ def deleteGcodeFile(filename, target): elif _verifyFolderExists(target, filename): if _isBusy(target, filename): - return make_response( - "Trying to delete a folder that contains a file that is currently in use", + 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 ce35d9ed5..1ba5c6f8d 100644 --- a/src/octoprint/server/api/job.py +++ b/src/octoprint/server/api/job.py @@ -5,7 +5,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 @@ -17,7 +17,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": []} @@ -34,22 +34,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": @@ -59,15 +60,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'", - 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 8ba9a05cf..46710b966 100644 --- a/src/octoprint/server/api/languages.py +++ b/src/octoprint/server/api/languages.py @@ -18,7 +18,7 @@ except ImportError: from collections import defaultdict -from flask import jsonify, make_response, request +from flask import abort, jsonify, request from flask_babel import Locale from octoprint.access.permissions import Permissions @@ -135,7 +135,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] @@ -146,8 +146,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") @@ -157,7 +158,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 307fa9e84..aa31caaae 100644 --- a/src/octoprint/server/api/printer.py +++ b/src/octoprint/server/api/printer.py @@ -7,9 +7,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import re -from flask import Response, jsonify, make_response, request +from flask import Response, abort, jsonify, request from past.builtins import basestring, long, unicode -from werkzeug.exceptions import BadRequest from octoprint.access.permissions import Permissions from octoprint.printer import UnknownScript @@ -25,7 +24,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 = [] @@ -75,7 +74,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"], @@ -96,9 +95,7 @@ def printerToolCommand(): if command == "select": tool = data["tool"] if not isinstance(tool, basestring) or re.match(validation_regex, tool) is None: - return make_response("Invalid tool", 400) - if not tool.startswith("tool"): - return make_response("Invalid tool for selection", 400) + abort(400, description="tool is invalid") printer.change_tool(tool, tags=tags) @@ -110,9 +107,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", 400) + abort(400, description="targets contains invalid tool") if not isinstance(value, (int, long, float)): - return make_response("Target is not a number", 400) + abort(400, description="targets contains invalid value") validated_values[tool] = value # perform the actual temperature commands @@ -127,11 +124,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 offset", 400) - if not isinstance(value, (int, long, float)): - return make_response("Offset is not a number", 400) - if not -50 <= value <= 50: - return make_response("Offset not in range [-50, 50]", 400) + abort(400, description="offsets contains invalid tool") + if not isinstance(value, (int, long, float)) or not -50 <= value <= 50: + abort(400, description="offsets contains invalid value") validated_values[tool] = value # set the offsets @@ -141,22 +136,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, long, float)): - return make_response("Extrusion amount is not a number", 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, long, float)): - return make_response("Flow rate is not a number", 400) + abort(400, description="factor is invalid") try: printer.flow_rate(factor, tags=tags) except ValueError: - return make_response("Invalid value for flow rate", 400) + abort(400, description="factor is invalid") return NO_CONTENT @@ -166,7 +161,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)) @@ -179,10 +174,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) @@ -197,7 +192,7 @@ def printerBedCommand(): # make sure the target is a number if not isinstance(target, (int, long, float)): - return make_response("Target is not a number", 400) + abort(400, description="target is invalid") # perform the actual temperature command printer.set_temperature("bed", target, tags=tags) @@ -207,10 +202,8 @@ def printerBedCommand(): offset = data["offset"] # make sure the offset is valid - if not isinstance(offset, (int, long, float)): - return make_response("Offset is not a number", 400) - if not -50 <= offset <= 50: - return make_response("Offset is not in range [-50, 50]", 400) + if not isinstance(offset, (int, long, float)) or not -50 <= offset <= 50: + abort(400, description="offset is invalid") # set the offsets printer.set_temperature_offset({"bed": offset}) @@ -223,10 +216,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): @@ -243,10 +236,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) @@ -261,7 +254,7 @@ def printerChamberCommand(): # make sure the target is a number if not isinstance(target, (int, long, float)): - return make_response("Target is not a number", 400) + abort(400, description="target is invalid") # perform the actual temperature command printer.set_temperature("chamber", target, tags=tags) @@ -271,10 +264,8 @@ def printerChamberCommand(): offset = data["offset"] # make sure the offset is valid - if not isinstance(offset, (int, long, float)): - return make_response("Offset is not a number", 400) - if not -50 <= offset <= 50: - return make_response("Offset is not in range [-50, 50]", 400) + if not isinstance(offset, (int, long, float)) or not -50 <= offset <= 50: + abort(400, description="offset is invalid") # set the offsets printer.set_temperature_offset({"chamber": offset}) @@ -287,10 +278,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): @@ -313,7 +304,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"} @@ -326,7 +317,7 @@ def printerPrintheadCommand(): if axis in data: value = data[axis] if not isinstance(value, (int, long, float)): - return make_response("Axis value is not a number", 400) + abort(400, description="axis value is invalid") validated_values[axis] = value absolute = "absolute" in data and data["absolute"] in valid_boolean_trues @@ -341,7 +332,7 @@ def printerPrintheadCommand(): axes = data["axes"] for axis in axes: if axis not in valid_axes: - return make_response("Invalid axis", 400) + abort(400, description="axis is invalid") validated_values.append(axis) # execute the home command @@ -350,11 +341,11 @@ def printerPrintheadCommand(): elif command == "feedrate": factor = data["factor"] if not isinstance(factor, (int, long, float)): - return make_response("Feed rate is not a number", 400) + abort(400, description="factor is invalid") try: printer.feed_rate(factor, tags=tags) except ValueError: - return make_response("Invalid value for feed rate", 400) + abort(400, description="factor is invalid") return NO_CONTENT @@ -367,10 +358,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) @@ -394,7 +385,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()) @@ -407,27 +398,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: @@ -440,7 +426,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 = [] @@ -461,7 +447,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 @@ -476,7 +462,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 cedf7b71f..01c69675c 100644 --- a/src/octoprint/server/api/printer_profiles.py +++ b/src/octoprint/server/api/printer_profiles.py @@ -8,9 +8,8 @@ __copyright__ = "Copyright (C) 2014 The OctoPrint Project - Released under terms import copy -from flask import jsonify, make_response, request, url_for +from flask import abort, jsonify, request, url_for from past.builtins import basestring -from werkzeug.exceptions import BadRequest from octoprint.access.permissions import Permissions from octoprint.printer.profile import CouldNotOverwriteError, InvalidProfileError @@ -60,18 +59,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"], basestring): @@ -95,23 +91,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", - 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)}) @@ -122,7 +115,7 @@ def printerProfilesAdd(): def printerProfilesGet(identifier): profile = printerProfileManager.get(identifier) if profile is None: - return make_response("Unknown profile", 404) + abort(404) else: return jsonify(_convert_profile(profile)) @@ -133,11 +126,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", 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", 409) + abort(409, description="Cannot delete default profile") printerProfileManager.remove(identifier, trigger_event=True) return NO_CONTENT @@ -148,18 +141,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 +172,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 3dec04a51..981ac93ed 100644 --- a/src/octoprint/server/api/settings.py +++ b/src/octoprint/server/api/settings.py @@ -7,10 +7,9 @@ __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 past.builtins import basestring -from werkzeug.exceptions import BadRequest import octoprint.plugin import octoprint.util @@ -373,22 +372,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".format(type(data).__name__), - 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: @@ -484,7 +472,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"]: diff --git a/src/octoprint/server/api/slicing.py b/src/octoprint/server/api/slicing.py index 94db08035..11ab033f8 100644 --- a/src/octoprint/server/api/slicing.py +++ b/src/octoprint/server/api/slicing.py @@ -5,8 +5,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 @@ -141,7 +140,7 @@ def slicingListSlicerProfiles(slicer): try: return jsonify(_getSlicingProfilesData(slicer, require_configured=configured)) except (UnknownSlicer, SlicerNotConfigured): - return make_response("Unknown slicer", 404) + abort(404) @api.route("/slicing//profiles/", methods=["GET"]) @@ -151,9 +150,9 @@ def slicingGetSlicerProfile(slicer, name): try: profile = slicingManager.load_profile(slicer, name, require_configured=False) except UnknownSlicer: - return make_response("Unknown slicer", 404) + abort(404) except UnknownProfile: - return make_response("Profile not found", 404) + abort(404) result = _getSlicingProfileData(slicer, name, profile) result["data"] = profile.data @@ -165,15 +164,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 @@ -195,7 +190,7 @@ def slicingAddSlicerProfile(slicer, name): description=description, ) except UnknownSlicer: - return make_response("Unknown slicer", 404) + abort(404, description="Unknown slicer") result = _getSlicingProfileData(slicer, name, profile) r = make_response(jsonify(result), 201) @@ -208,22 +203,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", 404) + return abort(404) except UnknownProfile: - return make_response("Profile for slicer not found", 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 @@ -260,11 +251,13 @@ def slicingDelSlicerProfile(slicer, name): try: slicingManager.delete_profile(slicer, name) except UnknownSlicer: - return make_response("Unknown slicer", 404) + abort(404) except CouldNotDeleteProfile as e: - return make_response( - "Could not delete profile for slicer: {cause}".format(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 6df204b8a..f863b3a6c 100644 --- a/src/octoprint/server/api/system.py +++ b/src/octoprint/server/api/system.py @@ -10,7 +10,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 @@ -87,7 +87,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"]) @@ -111,7 +111,7 @@ def retrieveSystemCommandsForSource(source): elif source == "custom": specs = _get_custom_command_specs() else: - return make_response("Unknown system command source", 404) + abort(404) return jsonify(_to_client_specs(specs)) @@ -123,16 +123,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", 404) + abort(404) if "command" not in command_spec: - return make_response( - "Command does not define a command to execute, can't proceed", - 500, + abort( + 500, description="Command does not define a command to execute, can't proceed" ) do_async = command_spec.get("async", False) @@ -155,7 +154,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: @@ -192,13 +191,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 80c5f2c28..0c630f46b 100644 --- a/src/octoprint/server/api/timelapse.py +++ b/src/octoprint/server/api/timelapse.py @@ -9,7 +9,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 @@ -182,7 +182,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() @@ -208,8 +208,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) @@ -231,56 +231,56 @@ def setTimelapseConfig(): try: postRoll = int(data["postRoll"]) except ValueError: - return make_response("Invalid value for postRoll", 400) + abort(400, description="postRoll is invalid") else: if postRoll >= 0: config["postRoll"] = postRoll else: - return make_response("Invalid value for 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", 400) + abort(400, description="fps is invalid") else: if fps > 0: config["fps"] = fps else: - return make_response("Invalid value for 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", 400) + abort(400, description="interval is invalid") else: if interval > 0: config["options"]["interval"] = interval else: - return make_response("Invalid value for 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", 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", 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", 400) + abort(400, description="minDelay is invalid") else: if minDelay > 0: config["options"]["minDelay"] = minDelay else: - return make_response("Invalid value for minimum delay", 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 bf1226797..f92d153c3 100644 --- a/src/octoprint/server/util/__init__.py +++ b/src/octoprint/server/util/__init__.py @@ -46,7 +46,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(): @@ -57,7 +57,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): @@ -118,7 +118,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 e565461bb..b5aa8597d 100644 --- a/src/octoprint/server/util/flask.py +++ b/src/octoprint/server/util/flask.py @@ -1305,11 +1305,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) @@ -1544,7 +1546,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 @@ -1566,9 +1568,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 @@ -1583,34 +1583,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