From 1ddb55d833cec8deefb17fcf7d939d515c903a10 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=2E=20Moukayed=20=28=D7=9B=D7=95=D7=9B=D7=91=29?= Date: Wed, 26 Sep 2018 00:14:40 +0200 Subject: [PATCH 1/3] aiohttpparser: Fix 500 error with JSON content-type and empty body --- webargs/aiohttpparser.py | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/webargs/aiohttpparser.py b/webargs/aiohttpparser.py index 8dac815b..e7d8e226 100644 --- a/webargs/aiohttpparser.py +++ b/webargs/aiohttpparser.py @@ -97,7 +97,14 @@ async def parse_json(self, req, name, field): if json_data is None: if not (req.body_exists and is_json_request(req)): return core.missing - self._cache["json"] = json_data = await req.json() + try: + json_data = await req.json() + except json.JSONDecodeError as e: + if e.doc == '': + return core.missing + else: + raise e + self._cache["json"] = json_data return core.get_value(json_data, name, field, allow_many_nested=True) def parse_headers(self, req, name, field): From c0cee7dd1649204acc2a8ae9c30e143892bcdcdb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=2E=20Moukayed=20=28=D7=9B=D7=95=D7=9B=D7=91=29?= Date: Wed, 26 Sep 2018 00:31:02 +0200 Subject: [PATCH 2/3] aiohttpparser: Use double quoted empty string This should make the PR pass the style check --- webargs/aiohttpparser.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/webargs/aiohttpparser.py b/webargs/aiohttpparser.py index e7d8e226..e3897a7e 100644 --- a/webargs/aiohttpparser.py +++ b/webargs/aiohttpparser.py @@ -100,7 +100,7 @@ async def parse_json(self, req, name, field): try: json_data = await req.json() except json.JSONDecodeError as e: - if e.doc == '': + if e.doc == "": return core.missing else: raise e From 7454c350452de96628b0a99e7a0caf10f4eda0ad Mon Sep 17 00:00:00 2001 From: Fadi Moukayed Date: Tue, 23 Oct 2018 20:58:43 +0200 Subject: [PATCH 3/3] test_aiohttpparser: Add a test to ensure correct behaviour on empty JSON bodies --- tests/test_aiohttpparser.py | 9 +++++++++ 1 file changed, 9 insertions(+) diff --git a/tests/test_aiohttpparser.py b/tests/test_aiohttpparser.py index 6e65afa3..93bcc782 100644 --- a/tests/test_aiohttpparser.py +++ b/tests/test_aiohttpparser.py @@ -1,9 +1,11 @@ # -*- coding: utf-8 -*- import asyncio +import webtest import webtest_aiohttp import pytest +from io import BytesIO from webargs.core import MARSHMALLOW_VERSION_INFO from webargs.testing import CommonTestCase from tests.apps.aiohttp_app import create_app @@ -63,3 +65,10 @@ def test_schema_as_kwargs_view(self, testapp): assert testapp.get("/echo_use_schema_as_kwargs?name=Chandler").json == { "name": "Chandler" } + + # https://github.com/sloria/webargs/pull/297 + def test_empty_json_body(self, testapp): + environ = {"CONTENT_TYPE": "application/json", "wsgi.input": BytesIO(b"")} + req = webtest.TestRequest.blank("/echo", environ) + resp = testapp.do_request(req) + assert resp.json == {"name": "World"}