/console/console/app/zip_loader.py

https://github.com/crass/app-engine-console · Python · 69 lines · 44 code · 13 blank · 12 comment · 8 complexity · 12a3d0066d27839307b207a334c21405 MD5 · raw file

  1. import os
  2. import re
  3. import logging
  4. import zipfile
  5. from django.conf import settings
  6. from django.template import TemplateDoesNotExist
  7. try:
  8. # in django 1.2 and greater
  9. from django.template.loader import BaseLoader
  10. except ImportError:
  11. class BaseLoader(object): pass
  12. class Loader(BaseLoader):
  13. is_usable = True
  14. zfname_re = re.compile("^(/.*/[^/]+.zip)(?:/(.*))?")
  15. #~ def get_template_sources(self, template_name, template_dirs=None):
  16. #~ pass
  17. def load_template_source(self, template_name, template_dirs=None):
  18. """Template loader that loads templates from a ZIP file."""
  19. if template_dirs is None:
  20. template_dirs = getattr(settings, "TEMPLATE_DIRS", tuple())
  21. # template_dirs is given by google as the dirname of the requested
  22. # template_path. If the dir has a zipfile in a component of its
  23. # path, then we need to read it from the zipfile.
  24. zfname_re = self.zfname_re
  25. tried = []
  26. for dir in template_dirs:
  27. # Does the dir indicate that it has a zipfile component?
  28. m = zfname_re.match(dir)
  29. if m:
  30. zfname = m.group(1)
  31. template_dir = m.group(2)
  32. template_path = os.path.join(template_dir, template_name)
  33. try:
  34. z = zipfile.ZipFile(zfname)
  35. source = z.read(template_path)
  36. except (IOError, KeyError):
  37. tried.append(dir)
  38. continue
  39. # We found a template, so return the source.
  40. template_path = "%s:%s" % (zfname, template_path)
  41. return (source, template_path)
  42. else:
  43. errmsg = "Failed to find %s in %s"%(template_name, tried)
  44. # If we reach here, the template couldn't be loaded
  45. raise TemplateDoesNotExist(errmsg)
  46. _loader = Loader()
  47. def load_template_source(template_name, template_dirs=None):
  48. # For backwards compatibility
  49. import warnings
  50. warnings.warn(
  51. "'zip_loader.load_template_source' is deprecated; use 'zip_loader.Loader' instead.",
  52. PendingDeprecationWarning
  53. )
  54. return _loader.load_template_source(template_name, template_dirs)
  55. # This loader is always usable (since zipfile is a Python standard library function)
  56. load_template_source.is_usable = True