template.py 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from __future__ import absolute_import
  2. import re
  3. import sys
  4. PY2 = sys.version_info[0] == 2
  5. if not PY2:
  6. text_type = str
  7. string_types = (str,)
  8. else:
  9. text_type = unicode
  10. string_types = (str, unicode)
  11. from datetime import datetime
  12. KEYWORDS_UP = ('ssl', 'uri', 'url', 'uuid', 'eta')
  13. KEYWORDS_DOWN = ('args', 'kwargs')
  14. UUID_REGEX = re.compile(r'^[\w]{8}(-[\w]{4}){3}-[\w]{12}$')
  15. def format_time(time):
  16. dt = datetime.fromtimestamp(time)
  17. return '%s.%s' % (
  18. dt.strftime("%Y-%m-%d %H:%M:%S"), dt.microsecond)
  19. def humanize(obj, type=None, length=None):
  20. if obj is None:
  21. obj = ''
  22. elif type == 'time':
  23. obj = format_time(float(obj)) if obj else '-'
  24. elif isinstance(obj, string_types) and not re.match(UUID_REGEX, obj):
  25. obj = obj.replace('-', ' ').replace('_', ' ')
  26. obj = re.sub('|'.join(KEYWORDS_UP),
  27. lambda m: m.group(0).upper(), obj)
  28. if obj and obj not in KEYWORDS_DOWN:
  29. obj = obj[0].upper() + obj[1:]
  30. elif isinstance(obj, list):
  31. if all(isinstance(x, (int, float) + string_types) for x in obj):
  32. obj = ', '.join(map(str, obj))
  33. if length is not None and len(obj) > length:
  34. obj = obj[:length - 4] + ' ...'
  35. return obj