You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
2.2 KiB

  1. """ A minimal jsonschema validator.
  2. Supports only a tiny subset of jsonschema.
  3. """
  4. from croniter import croniter
  5. from pytz import all_timezones
  6. class ValidationError(Exception):
  7. pass
  8. def validate(obj, schema, obj_name="value"):
  9. if schema.get("type") == "string":
  10. if not isinstance(obj, str):
  11. raise ValidationError("%s is not a string" % obj_name)
  12. if "minLength" in schema and len(obj) < schema["minLength"]:
  13. raise ValidationError("%s is too short" % obj_name)
  14. if "maxLength" in schema and len(obj) > schema["maxLength"]:
  15. raise ValidationError("%s is too long" % obj_name)
  16. if schema.get("format") == "cron":
  17. try:
  18. croniter(obj)
  19. except:
  20. raise ValidationError("%s is not a valid cron expression" % obj_name)
  21. if schema.get("format") == "timezone" and obj not in all_timezones:
  22. raise ValidationError("%s is not a valid timezone" % obj_name)
  23. elif schema.get("type") == "number":
  24. if not isinstance(obj, int):
  25. raise ValidationError("%s is not a number" % obj_name)
  26. if "minimum" in schema and obj < schema["minimum"]:
  27. raise ValidationError("%s is too small" % obj_name)
  28. if "maximum" in schema and obj > schema["maximum"]:
  29. raise ValidationError("%s is too large" % obj_name)
  30. elif schema.get("type") == "array":
  31. if not isinstance(obj, list):
  32. raise ValidationError("%s is not an array" % obj_name)
  33. for v in obj:
  34. validate(v, schema["items"], "an item in '%s'" % obj_name)
  35. elif schema.get("type") == "object":
  36. if not isinstance(obj, dict):
  37. raise ValidationError("%s is not an object" % obj_name)
  38. properties = schema.get("properties", {})
  39. for key, spec in properties.items():
  40. if key in obj:
  41. validate(obj[key], spec, obj_name=key)
  42. for key in schema.get("required", []):
  43. if key not in obj:
  44. raise ValidationError("key %s absent in %s" % (key, obj_name))
  45. if "enum" in schema:
  46. if obj not in schema["enum"]:
  47. raise ValidationError("%s has unexpected value" % obj_name)