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.

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