gzip_cache.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. '''
  2. Copyright (c) 2012 Matt Layman
  3. Gzip cache
  4. ----------
  5. A plugin to create .gz cache files for optimization.
  6. '''
  7. import gzip
  8. import logging
  9. import os
  10. from pelican import signals
  11. logger = logging.getLogger(__name__)
  12. # A list of file types to exclude from possible compression
  13. EXCLUDE_TYPES = [
  14. # Compressed types
  15. '.bz2',
  16. '.gz',
  17. # Audio types
  18. '.aac',
  19. '.flac',
  20. '.mp3',
  21. '.wma',
  22. # Image types
  23. '.gif',
  24. '.jpg',
  25. '.jpeg',
  26. '.png',
  27. # Video types
  28. '.avi',
  29. '.mov',
  30. '.mp4',
  31. ]
  32. def create_gzip_cache(pelican):
  33. '''Create a gzip cache file for every file that a webserver would
  34. reasonably want to cache (e.g., text type files).
  35. :param pelican: The Pelican instance
  36. '''
  37. for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']):
  38. for name in filenames:
  39. if should_compress(name):
  40. filepath = os.path.join(dirpath, name)
  41. create_gzip_file(filepath)
  42. def should_compress(filename):
  43. '''Check if the filename is a type of file that should be compressed.
  44. :param filename: A file name to check against
  45. '''
  46. for extension in EXCLUDE_TYPES:
  47. if filename.endswith(extension):
  48. return False
  49. return True
  50. def create_gzip_file(filepath):
  51. '''Create a gzipped file in the same directory with a filepath.gz name.
  52. :param filepath: A file to compress
  53. '''
  54. compressed_path = filepath + '.gz'
  55. with open(filepath, 'rb') as uncompressed:
  56. # Explicitly set mtime to 0 so gzip content is fully determined
  57. # by file content (0 = "no timestamp" according to gzip spec)
  58. with gzip.GzipFile(compressed_path, 'wb',
  59. compresslevel=9, mtime=0) as compressed:
  60. logger.debug('Compressing: %s' % filepath)
  61. try:
  62. compressed.writelines(uncompressed)
  63. except Exception as ex:
  64. logger.critical('Gzip compression failed: %s' % ex)
  65. def register():
  66. signals.finalized.connect(create_gzip_cache)