compat.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. # -*- coding: utf-8 -*-
  2. from io import BytesIO
  3. import csv
  4. import codecs
  5. import importlib
  6. from django.conf import settings
  7. #
  8. # Django compatibility
  9. #
  10. def load_tag_library(libname):
  11. """
  12. Load a templatetag library on multiple Django versions.
  13. Returns None if the library isn't loaded.
  14. """
  15. from django.template.backends.django import get_installed_libraries
  16. from django.template.library import InvalidTemplateLibrary
  17. try:
  18. lib = get_installed_libraries()[libname]
  19. lib = importlib.import_module(lib).register
  20. return lib
  21. except (InvalidTemplateLibrary, KeyError):
  22. return None
  23. def get_template_setting(template_key, default=None):
  24. """ Read template settings """
  25. templates_var = getattr(settings, 'TEMPLATES', None)
  26. if templates_var:
  27. for tdict in templates_var:
  28. if template_key in tdict:
  29. return tdict[template_key]
  30. return default
  31. class UnicodeWriter:
  32. """
  33. CSV writer which will write rows to CSV file "f",
  34. which is encoded in the given encoding.
  35. We are using this custom UnicodeWriter for python versions 2.x
  36. """
  37. def __init__(self, f, dialect=csv.excel, encoding="utf-8", **kwds):
  38. self.queue = BytesIO()
  39. self.writer = csv.writer(self.queue, dialect=dialect, **kwds)
  40. self.stream = f
  41. self.encoder = codecs.getincrementalencoder(encoding)()
  42. def writerow(self, row):
  43. self.writer.writerow([s.encode("utf-8") for s in row])
  44. # Fetch UTF-8 output from the queue ...
  45. data = self.queue.getvalue()
  46. data = data.decode("utf-8")
  47. # ... and reencode it into the target encoding
  48. data = self.encoder.encode(data)
  49. # write to the target stream
  50. self.stream.write(data)
  51. # empty queue
  52. self.queue.truncate(0)
  53. def writerows(self, rows):
  54. for row in rows:
  55. self.writerow(row)