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.

60 lines
2.1 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 "maxLength" in schema and len(obj) > schema["maxLength"]:
  13. raise ValidationError("%s is too long" % obj_name)
  14. if schema.get("format") == "cron":
  15. try:
  16. croniter(obj)
  17. except:
  18. raise ValidationError(
  19. "%s is not a valid cron expression" % obj_name)
  20. if schema.get("format") == "timezone" and obj not in all_timezones:
  21. raise ValidationError("%s is not a valid timezone" % obj_name)
  22. elif schema.get("type") == "number":
  23. if not isinstance(obj, int):
  24. raise ValidationError("%s is not a number" % obj_name)
  25. if "minimum" in schema and obj < schema["minimum"]:
  26. raise ValidationError("%s is too small" % obj_name)
  27. if "maximum" in schema and obj > schema["maximum"]:
  28. raise ValidationError("%s is too large" % obj_name)
  29. elif schema.get("type") == "array":
  30. if not isinstance(obj, list):
  31. raise ValidationError("%s is not an array" % obj_name)
  32. for v in obj:
  33. validate(v, schema["items"], "an item in '%s'" % obj_name)
  34. elif schema.get("type") == "object":
  35. if not isinstance(obj, dict):
  36. raise ValidationError("%s is not an object" % obj_name)
  37. properties = schema.get("properties", {})
  38. for key, spec in properties.items():
  39. if key in obj:
  40. validate(obj[key], spec, obj_name=key)
  41. for key in schema.get("required", []):
  42. if key not in obj:
  43. raise ValidationError("key %s absent in %s" % (key, obj_name))
  44. if "enum" in schema:
  45. if obj not in schema["enum"]:
  46. raise ValidationError("%s has unexpected value" % obj_name)