From a9f34dab93acc28edf382f95fef7ebd97a5c78ec Mon Sep 17 00:00:00 2001 From: Alexey Subbotin Date: Wed, 12 Apr 2017 12:25:51 +0200 Subject: [PATCH] `request.body` might raise RawPostDataException, RequestDataTooBig, UnreadablePostError exceptions which are not related to invalid JSON data --- graphene_django/tests/test_views.py | 11 +++++++++++ graphene_django/views.py | 11 ++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/graphene_django/tests/test_views.py b/graphene_django/tests/test_views.py index 7293423..23a8f72 100644 --- a/graphene_django/tests/test_views.py +++ b/graphene_django/tests/test_views.py @@ -457,6 +457,17 @@ def test_handles_invalid_json_bodies(client): } +def test_handles_django_request_error(client, settings): + settings.DATA_UPLOAD_MAX_MEMORY_SIZE = 1000 + valid_json = json.dumps(dict(test='x' * 1000)) + response = client.post(url_string(), valid_json, 'application/json') + + assert response.status_code == 400 + assert response_json(response) == { + 'errors': [{'message': 'Request body exceeded settings.DATA_UPLOAD_MAX_MEMORY_SIZE.'}] + } + + def test_handles_incomplete_json_bodies(client): response = client.post(url_string(), '{"query":', 'application/json') diff --git a/graphene_django/views.py b/graphene_django/views.py index 4129668..afe04d7 100644 --- a/graphene_django/views.py +++ b/graphene_django/views.py @@ -179,7 +179,6 @@ class GraphQLView(View): return json.dumps(d, sort_keys=True, indent=2, separators=(',', ': ')) - # noinspection PyBroadException def parse_body(self, request): content_type = self.get_content_type(request) @@ -187,8 +186,14 @@ class GraphQLView(View): return {'query': request.body.decode()} elif content_type == 'application/json': + # noinspection PyBroadException try: - request_json = json.loads(request.body.decode('utf-8')) + body = request.body.decode('utf-8') + except Exception as e: + raise HttpError(HttpResponseBadRequest(str(e))) + + try: + request_json = json.loads(body) if self.batch: assert isinstance(request_json, list), ( 'Batch requests should receive a list, but received {}.' @@ -203,7 +208,7 @@ class GraphQLView(View): return request_json except AssertionError as e: raise HttpError(HttpResponseBadRequest(str(e))) - except: + except (TypeError, ValueError): raise HttpError(HttpResponseBadRequest('POST body sent invalid JSON.')) elif content_type in ['application/x-www-form-urlencoded', 'multipart/form-data']: