No puede seleccionar más de 25 temas Los temas deben comenzar con una letra o número, pueden incluir guiones ('-') y pueden tener hasta 35 caracteres de largo.
 
 
 
 

82 líneas
2.0 KiB

  1. import math
  2. import typing
  3. import uuid
  4. class Convertor:
  5. regex = ""
  6. def convert(self, value: str) -> typing.Any:
  7. raise NotImplementedError() # pragma: no cover
  8. def to_string(self, value: typing.Any) -> str:
  9. raise NotImplementedError() # pragma: no cover
  10. class StringConvertor(Convertor):
  11. regex = "[^/]+"
  12. def convert(self, value: str) -> typing.Any:
  13. return value
  14. def to_string(self, value: typing.Any) -> str:
  15. value = str(value)
  16. assert "/" not in value, "May not contain path separators"
  17. assert value, "Must not be empty"
  18. return value
  19. class PathConvertor(Convertor):
  20. regex = ".*"
  21. def convert(self, value: str) -> typing.Any:
  22. return str(value)
  23. def to_string(self, value: typing.Any) -> str:
  24. return str(value)
  25. class IntegerConvertor(Convertor):
  26. regex = "[0-9]+"
  27. def convert(self, value: str) -> typing.Any:
  28. return int(value)
  29. def to_string(self, value: typing.Any) -> str:
  30. value = int(value)
  31. assert value >= 0, "Negative integers are not supported"
  32. return str(value)
  33. class FloatConvertor(Convertor):
  34. regex = "[0-9]+(.[0-9]+)?"
  35. def convert(self, value: str) -> typing.Any:
  36. return float(value)
  37. def to_string(self, value: typing.Any) -> str:
  38. value = float(value)
  39. assert value >= 0.0, "Negative floats are not supported"
  40. assert not math.isnan(value), "NaN values are not supported"
  41. assert not math.isinf(value), "Infinite values are not supported"
  42. return ("%0.20f" % value).rstrip("0").rstrip(".")
  43. class UUIDConvertor(Convertor):
  44. regex = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
  45. def convert(self, value: str) -> typing.Any:
  46. return uuid.UUID(value)
  47. def to_string(self, value: typing.Any) -> str:
  48. return str(value)
  49. CONVERTOR_TYPES = {
  50. "str": StringConvertor(),
  51. "path": PathConvertor(),
  52. "int": IntegerConvertor(),
  53. "float": FloatConvertor(),
  54. "uuid": UUIDConvertor(),
  55. }