Development of an internal social media platform with personalised dashboards for students
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

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import uuid
  2. from django.utils 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.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]