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.

56 lines
1.9 KiB

  1. """ A minimal jsonschema validator.
  2. Supports only a tiny subset of jsonschema.
  3. """
  4. from croniter import croniter
  5. from six import string_types
  6. from pytz import all_timezones
  7. class ValidationError(Exception):
  8. pass
  9. def validate(obj, schema, obj_name="value"):
  10. if schema.get("type") == "string":
  11. if not isinstance(obj, string_types):
  12. raise ValidationError("%s is not a string" % obj_name)
  13. if "maxLength" in schema and len(obj) > schema["maxLength"]:
  14. raise ValidationError("%s is too long" % obj_name)
  15. if schema.get("format") == "cron":
  16. try:
  17. croniter(obj)
  18. except:
  19. raise ValidationError(
  20. "%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. for key, spec in schema["properties"].items():
  39. if key in obj:
  40. validate(obj[key], spec, obj_name=key)
  41. if "enum" in schema:
  42. if obj not in schema["enum"]:
  43. raise ValidationError("%s has unexpected value" % obj_name)