← Lesson
Required Fields and Extra Keys
Joeven
Run
Reset
Python loads on first run
PROPS = {"city": {"type": "string"}, "limit": {"type": "integer"}} REQUIRED = ["city"] def validate(args): if not isinstance(args, dict): return ["not_object"] errors = [] for key in REQUIRED: if key not in args: errors.append("missing " + key) for key in args: if key not in PROPS: errors.append("unknown field " + key) city = args.get("city") if "city" in args and (not isinstance(city, str) or not city.strip()): errors.append("city empty") if "limit" in args and not isinstance(args["limit"], int): errors.append("limit not integer") return errors tests = [ {"city": "Paris"}, {"city": "Paris", "limit": 3}, {"city": "Paris", "sql": "DROP TABLE cities"}, {"limit": 3}, {"city": " "}, ] for t in tests: print(t, "->", validate(t) or "ok")
Run to execute this in your browser. Nothing is sent to a server.