Created
July 12, 2021 18:20
-
-
Save Lessica/440d68a338011aedd15fddac78bbd883 to your computer and use it in GitHub Desktop.
Validate JSON request data
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def expects_json(obj: dict, schema: tuple): | |
# or use library `flask-expects-json` | |
_type = type(obj) | |
if _type != dict: | |
raise werkzeug.exceptions.BadRequest(f"wrong type of root object, except dict, got {str(_type.__name__)}") | |
_keys = schema | |
for _key in _keys: | |
assert len(_key) >= 2 | |
if _key[0] not in obj: | |
if len(_key) >= 3 and _key[2] is False: | |
continue | |
raise werkzeug.exceptions.BadRequest(f"missing required parameter: {_key[0]}") | |
_type = type(obj[_key[0]]) | |
if _type != _key[1]: | |
raise werkzeug.exceptions.BadRequest( | |
f"wrong type of {'optional' if len(_key) >= 3 and _key[2] is False else 'required'} parameter: " | |
f"{_key[0]}, excepted {str(_key[1].__name__)}, got {str(_type.__name__)}" | |
) | |
# usage | |
challenge_dict = request.get_json() | |
if request.method != 'POST': | |
raise BadRequest("POST only") | |
expects_json(challenge_dict, ( | |
# name, type, required (default is True), ... | |
("person", dict,), | |
("questionText", str,), | |
("answers", list,), | |
)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment