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.

68 lines
2.5 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. # Does croniter accept the schedule?
  19. it = croniter(obj)
  20. # Can it calculate the next datetime?
  21. it.next()
  22. except:
  23. raise ValidationError("%s is not a valid cron expression" % obj_name)
  24. if schema.get("format") == "timezone" and obj not in all_timezones:
  25. raise ValidationError("%s is not a valid timezone" % obj_name)
  26. elif schema.get("type") == "number":
  27. if not isinstance(obj, int):
  28. raise ValidationError("%s is not a number" % obj_name)
  29. if "minimum" in schema and obj < schema["minimum"]:
  30. raise ValidationError("%s is too small" % obj_name)
  31. if "maximum" in schema and obj > schema["maximum"]:
  32. raise ValidationError("%s is too large" % obj_name)
  33. elif schema.get("type") == "boolean":
  34. if not isinstance(obj, bool):
  35. raise ValidationError("%s is not a boolean" % obj_name)
  36. elif schema.get("type") == "array":
  37. if not isinstance(obj, list):
  38. raise ValidationError("%s is not an array" % obj_name)
  39. for v in obj:
  40. validate(v, schema["items"], "an item in '%s'" % obj_name)
  41. elif schema.get("type") == "object":
  42. if not isinstance(obj, dict):
  43. raise ValidationError("%s is not an object" % obj_name)
  44. properties = schema.get("properties", {})
  45. for key, spec in properties.items():
  46. if key in obj:
  47. validate(obj[key], spec, obj_name=key)
  48. for key in schema.get("required", []):
  49. if key not in obj:
  50. raise ValidationError("key %s absent in %s" % (key, obj_name))
  51. if "enum" in schema:
  52. if obj not in schema["enum"]:
  53. raise ValidationError("%s has unexpected value" % obj_name)