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.

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