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.

converters.py 1.2KB

5 years ago
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. import uuid
  2. from functools import lru_cache
  3. class IntConverter:
  4. regex = '[0-9]+'
  5. def to_python(self, value):
  6. return int(value)
  7. def to_url(self, value):
  8. return str(value)
  9. class StringConverter:
  10. regex = '[^/]+'
  11. def to_python(self, value):
  12. return value
  13. def to_url(self, value):
  14. return value
  15. class UUIDConverter:
  16. regex = '[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}'
  17. def to_python(self, value):
  18. return uuid.UUID(value)
  19. def to_url(self, value):
  20. return str(value)
  21. class SlugConverter(StringConverter):
  22. regex = '[-a-zA-Z0-9_]+'
  23. class PathConverter(StringConverter):
  24. regex = '.+'
  25. DEFAULT_CONVERTERS = {
  26. 'int': IntConverter(),
  27. 'path': PathConverter(),
  28. 'slug': SlugConverter(),
  29. 'str': StringConverter(),
  30. 'uuid': UUIDConverter(),
  31. }
  32. REGISTERED_CONVERTERS = {}
  33. def register_converter(converter, type_name):
  34. REGISTERED_CONVERTERS[type_name] = converter()
  35. get_converters.cache_clear()
  36. @lru_cache(maxsize=None)
  37. def get_converters():
  38. return {**DEFAULT_CONVERTERS, **REGISTERED_CONVERTERS}
  39. def get_converter(raw_converter):
  40. return get_converters()[raw_converter]