strings.py 1019 B

123456789101112131415161718192021222324252627282930313233343536
  1. from django.template.defaultfilters import slugify as django_slugify
  2. from django.utils import crypto
  3. try:
  4. from unidecode import unidecode
  5. use_unidecode = True
  6. except ImportError:
  7. use_unidecode = False
  8. def slugify(string):
  9. string = unicode(string)
  10. if use_unidecode:
  11. string = unidecode(string)
  12. return django_slugify(string)
  13. def random_string(length):
  14. return crypto.get_random_string(length, "1234567890qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM")
  15. def short_string(string, length=16):
  16. if len(string) <= length:
  17. return string;
  18. length -= 3
  19. string = string[0:length]
  20. bits = string.split()
  21. if len(bits[-1]) > length:
  22. bits[-1] = bits[-1][0:length]
  23. if len(bits[-1]) < 3:
  24. bits.pop()
  25. return '%s...' % (' '.join(bits))
  26. def html_escape(html):
  27. html = html.replace('&', '&amp;')
  28. html = html.replace('<', '&lt;')
  29. html = html.replace('>', '&gt;')
  30. return html.replace('"', '&quot;')