representation.py 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. """
  2. Helper functions for creating user-friendly representations
  3. of serializer classes and serializer fields.
  4. """
  5. import re
  6. from django.db import models
  7. from django.utils.encoding import force_str
  8. from django.utils.functional import Promise
  9. def manager_repr(value):
  10. model = value.model
  11. opts = model._meta
  12. names_and_managers = [
  13. (manager.name, manager)
  14. for manager
  15. in opts.managers
  16. ]
  17. for manager_name, manager_instance in names_and_managers:
  18. if manager_instance == value:
  19. return '%s.%s.all()' % (model._meta.object_name, manager_name)
  20. return repr(value)
  21. def smart_repr(value):
  22. if isinstance(value, models.Manager):
  23. return manager_repr(value)
  24. if isinstance(value, Promise) and value._delegate_text:
  25. value = force_str(value)
  26. value = repr(value)
  27. # Representations like u'help text'
  28. # should simply be presented as 'help text'
  29. if value.startswith("u'") and value.endswith("'"):
  30. return value[1:]
  31. # Representations like
  32. # <django.core.validators.RegexValidator object at 0x1047af050>
  33. # Should be presented as
  34. # <django.core.validators.RegexValidator object>
  35. return re.sub(' at 0x[0-9A-Fa-f]{4,32}>', '>', value)
  36. def field_repr(field, force_many=False):
  37. kwargs = field._kwargs
  38. if force_many:
  39. kwargs = kwargs.copy()
  40. kwargs['many'] = True
  41. kwargs.pop('child', None)
  42. arg_string = ', '.join([smart_repr(val) for val in field._args])
  43. kwarg_string = ', '.join([
  44. '%s=%s' % (key, smart_repr(val))
  45. for key, val in sorted(kwargs.items())
  46. ])
  47. if arg_string and kwarg_string:
  48. arg_string += ', '
  49. if force_many:
  50. class_name = force_many.__class__.__name__
  51. else:
  52. class_name = field.__class__.__name__
  53. return "%s(%s%s)" % (class_name, arg_string, kwarg_string)
  54. def serializer_repr(serializer, indent, force_many=None):
  55. ret = field_repr(serializer, force_many) + ':'
  56. indent_str = ' ' * indent
  57. if force_many:
  58. fields = force_many.fields
  59. else:
  60. fields = serializer.fields
  61. for field_name, field in fields.items():
  62. ret += '\n' + indent_str + field_name + ' = '
  63. if hasattr(field, 'fields'):
  64. ret += serializer_repr(field, indent + 1)
  65. elif hasattr(field, 'child'):
  66. ret += list_repr(field, indent + 1)
  67. elif hasattr(field, 'child_relation'):
  68. ret += field_repr(field.child_relation, force_many=field.child_relation)
  69. else:
  70. ret += field_repr(field)
  71. if serializer.validators:
  72. ret += '\n' + indent_str + 'class Meta:'
  73. ret += '\n' + indent_str + ' validators = ' + smart_repr(serializer.validators)
  74. return ret
  75. def list_repr(serializer, indent):
  76. child = serializer.child
  77. if hasattr(child, 'fields'):
  78. return serializer_repr(serializer, indent, force_many=child)
  79. return field_repr(serializer)