From 15f734d21b79d9657e93c7f8987163bfc560c7ce Mon Sep 17 00:00:00 2001 From: rr- Date: Tue, 19 Apr 2016 12:40:08 +0200 Subject: [PATCH] server/api: output JSON for HTTP 405 --- server/szurubooru/app.py | 16 ++++++++++++++++ server/szurubooru/middleware/context_adapter.py | 11 +++++------ 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/server/szurubooru/app.py b/server/szurubooru/app.py index fd4dd6c..74d9af3 100644 --- a/server/szurubooru/app.py +++ b/server/szurubooru/app.py @@ -1,5 +1,6 @@ ''' Exports create_app. ''' +import json import falcon from szurubooru import api, errors, middleware @@ -23,8 +24,23 @@ def _on_not_found_error(ex, _request, _response, _params): def _on_processing_error(ex, _request, _response, _params): raise falcon.HTTPBadRequest(title='Processing error', description=str(ex)) +def create_method_not_allowed(allowed_methods): + allowed = ', '.join(allowed_methods) + + def method_not_allowed(request, response, **kwargs): + response.status = falcon.status_codes.HTTP_405 + response.set_header('Allow', allowed) + request.context.output = { + 'title': 'Method not allowed', + 'description': 'Allowed methods: %r' % allowed_methods, + } + + return method_not_allowed + def create_app(): ''' Create a WSGI compatible App object. ''' + falcon.responders.create_method_not_allowed = create_method_not_allowed + app = falcon.API( request_type=api.Request, middleware=[ diff --git a/server/szurubooru/middleware/context_adapter.py b/server/szurubooru/middleware/context_adapter.py index 464c277..fb79f44 100644 --- a/server/szurubooru/middleware/context_adapter.py +++ b/server/szurubooru/middleware/context_adapter.py @@ -21,6 +21,7 @@ class ContextAdapter(object): def process_request(self, request, _response): request.context.files = {} request.context.input = {} + request.context.output = None # pylint: disable=protected-access for key, value in request._params.items(): request.context.input[key] = value @@ -53,14 +54,12 @@ class ContextAdapter(object): for key, value in json.loads(body).items(): request.context.input[key] = value except (ValueError, UnicodeDecodeError): - raise falcon.HTTPError( - falcon.HTTP_401, + raise falcon.HTTPBadRequest( 'Malformed JSON', 'Could not decode the request body. The ' 'JSON was incorrect or not encoded as UTF-8.') def process_response(self, request, response, _resource): - if not request.context.output: - return - response.body = json.dumps( - request.context.output, default=json_serializer, indent=2) + if request.context.output: + response.body = json.dumps( + request.context.output, default=json_serializer, indent=2)