def on_get(self, req, resp): try: parsed = parser.parse(hello_args, req) except json.JSONDecodeError: resp.body = json.dumps(["Invalid JSON."]) resp.status = falcon.HTTP_400 else: resp.body = json.dumps(parsed)
def on_get(self, req, resp): class HeaderSchema(ma.Schema): NAME = fields.Str(missing="World") resp.body = json.dumps( parser.parse(HeaderSchema(**exclude_kwargs), req, location="headers") )
def handle_invalid_json_error(self, error: json.JSONDecodeError, req: Request, *args, **kwargs) -> "typing.NoReturn": error_class = exception_map[400] messages = {"json": ["Invalid JSON body."]} raise error_class(body=json.dumps(messages).encode("utf-8"), content_type="application/json")
def on_post(self, req, resp): args = { "users": fields.Nested( {"id": fields.Int(), "name": fields.Str()}, many=True ) } resp.body = json.dumps(parser.parse(args, req))
def test_parse_json_with_charset(self, testapp): res = testapp.post( "/echo_json", json.dumps({"name": "Steve"}), content_type="application/json;charset=UTF-8", ) assert res.json == {"name": "Steve"}
def test_parse_json(): expected = {"name": "Fred"} request = webapp2.Request.blank( "/echo", POST=json.dumps(expected), headers={"content-type": "application/json"}) assert parser.parse(hello_args, req=request) == expected
def test_parse_json_content_type_mismatch(): request = webapp2.Request.blank( "/echo_json", POST=json.dumps({"name": "foo"}), headers={"content-type": "application/x-www-form-urlencoded"}, ) assert parser.parse(hello_args, req=request) == {"name": "World"}
def test_parse_json_with_vendor_media_type(self, testapp): res = testapp.post( "/echo", json.dumps({"name": "Steve"}), content_type="application/vnd.api+json;charset=UTF-8", ) assert res.json == {"name": "Steve"}
def _handle_invalid_json_error(self, error, req, *args, **kwargs): messages = {"json": ["Invalid JSON body."]} response = exception_response(400, detail=str(messages), content_type="application/json") body = json.dumps(messages) response.body = body.encode("utf-8") if isinstance(body, str) else body raise response
def echo_json_ignore_extra_data(request): try: return parser.parse(hello_exclude_schema, request) except json.JSONDecodeError: error = HTTPBadRequest() error.body = json.dumps(["Invalid JSON."]).encode("utf-8") error.content_type = "application/json" raise error
def echo_json_or_form(request): try: return parser.parse(hello_args, request, location="json_or_form") except json.JSONDecodeError: error = HTTPBadRequest() error.body = json.dumps(["Invalid JSON."]).encode("utf-8") error.content_type = "application/json" raise error
def test_parse_json_with_vendor_media_type(): expected = {"name": "Fred"} request = webapp2.Request.blank( "/echo", POST=json.dumps(expected), headers={"content-type": "application/vnd.api+json"}, ) assert parser.parse(hello_args, req=request) == expected
def post(self, args): self.response.content_type = "application/json" def _value(f): return f.getvalue().decode("utf-8") data = dict((i.filename, _value(i.file)) for i in args["myfile"]) self.response.write(json.dumps(data))
def thread_fn(value): with app.test_request_context( "/foo", method="post", data=json.dumps({"value": value}), content_type="application/json", ): results[value] = parser.parse(argmap)["value"]
def test_user_validator_returns_422_by_default(self): res = self.fetch( "/alwaysfail", method="POST", headers={"Content-Type": "application/json"}, body=json.dumps({"name": "Steve"}), ) assert res.code == 422
def test_missing_required_field_throws_422(self): res = self.fetch( "/echo", method="POST", headers={"Content-Type": "application/json"}, body=json.dumps({"occupation": "pizza"}), ) assert res.code == 422
def test_post(self): res = self.fetch( "/echo_json", method="POST", headers={"Content-Type": "application/json"}, body=json.dumps({"name": "Steve"}), ) json_body = parse_json(res.body) assert json_body["name"] == "Steve" res = self.fetch( "/echo_json", method="POST", headers={"Content-Type": "application/json"}, body=json.dumps({}), ) json_body = parse_json(res.body) assert "name" not in json_body
def on_post(self, req, resp): args = { "name": fields.Nested({ "first": fields.Str(), "last": fields.Str() }) } resp.body = json.dumps(parser.parse(args, req))
def test_required_field_provided(self): res = self.fetch( "/echo", method="POST", headers={"Content-Type": "application/json"}, body=json.dumps({"name": "johnny"}), ) json_body = parse_json(res.body) assert json_body["name"] == "johnny"
async def echo_json(request): try: parsed = await parser.parse(hello_args, request, location="json") except json.JSONDecodeError: raise aiohttp.web.HTTPBadRequest( body=json.dumps(["Invalid JSON."]).encode("utf-8"), content_type="application/json", ) return json_response(parsed)
def test_abort_has_serializable_data(): with pytest.raises(HTTPException) as excinfo: abort(400, message="custom error message") serialized_error = json.dumps(excinfo.value.data) error = json.loads(serialized_error) assert isinstance(error, dict) assert error["message"] == "custom error message" with pytest.raises(HTTPException) as excinfo: abort( 400, message="custom error message", exc=ValidationError("custom error message"), ) serialized_error = json.dumps(excinfo.value.data) error = json.loads(serialized_error) assert isinstance(error, dict) assert error["message"] == "custom error message"
def handle_error(self, error, req, schema, *, error_status_code, error_headers): """Handles errors during parsing. Aborts the current HTTP request and responds with a 400 error. """ status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS response = exception_response( status_code, detail=str(error), headers=error_headers, content_type="application/json", ) body = json.dumps(error.messages) response.body = body.encode("utf-8") if isinstance(body, str) else body raise response
def handle_error( self, error: ValidationError, req: Request, schema: Schema, *, error_status_code: typing.Union[int, None], error_headers: typing.Union[typing.Mapping[str, str], None] ) -> typing.NoReturn: """Handle ValidationErrors and return a JSON response of error messages to the client. """ error_class = exception_map.get(error_status_code or self.DEFAULT_VALIDATION_STATUS) if not error_class: raise LookupError(f"No exception for {error_status_code}") headers = error_headers raise error_class( body=json.dumps(error.messages).encode("utf-8"), headers=headers, content_type="application/json", )
def test_abort_called_on_validation_error(mock_abort): app = Flask("testapp") def validate(x): return x == 42 argmap = {"value": fields.Field(validate=validate)} with app.test_request_context( "/foo", method="post", data=json.dumps({"value": 41}), content_type="application/json", ): parser.parse(argmap) mock_abort.assert_called abort_args, abort_kwargs = mock_abort.call_args assert abort_args[0] == 422 expected_msg = "Invalid value." assert abort_kwargs["messages"]["value"] == [expected_msg] assert type(abort_kwargs["exc"]) == ValidationError
def test_abort_called_on_validation_error(mock_abort): # error handling must raise an error to be valid mock_abort.side_effect = BadRequest("foo") app = Flask("testapp") def validate(x): return x == 42 argmap = {"value": fields.Field(validate=validate)} with app.test_request_context( "/foo", method="post", data=json.dumps({"value": 41}), content_type="application/json", ): with pytest.raises(HTTPException): parser.parse(argmap) mock_abort.assert_called() abort_args, abort_kwargs = mock_abort.call_args assert abort_args[0] == 422 expected_msg = "Invalid value." assert abort_kwargs["messages"]["json"]["value"] == [expected_msg] assert type(abort_kwargs["exc"]) == ValidationError
def make_json_body(args): return json.dumps(args)
def on_get(self, req, resp): def always_fail(value): raise ma.ValidationError("something went wrong") args = {"text": fields.Str(validate=always_fail)} resp.body = json.dumps(parser.parse(args, req))
def on_get(self, req, resp, value, name): resp.body = json.dumps({"value": value})
def on_get(self, req, resp, args, name): resp.body = json.dumps(args)
def on_get(self, req, resp): resp.body = json.dumps( parser.parse(hello_many_schema, req, locations=("json",)) )