compat.py 1.9 KB

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