gzip_cache.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. '''
  2. Copyright (c) 2012 Matt Layman
  3. Gzip cache
  4. ----------
  5. A plugin to create .gz cache files for optimization.
  6. '''
  7. import logging
  8. import os
  9. import zlib
  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. COMPRESSION_LEVEL = 9 # Best Compression
  33. """ According to zlib manual: 'Add 16 to
  34. windowBits to write a simple gzip header and trailer around the
  35. compressed data instead of a zlib wrapper. The gzip header will
  36. have no file name, no extra data, no comment, no modification
  37. time (set to zero), no header crc, and the operating system
  38. will be set to 255 (unknown)'
  39. """
  40. WBITS = zlib.MAX_WBITS | 16
  41. def create_gzip_cache(pelican):
  42. '''Create a gzip cache file for every file that a webserver would
  43. reasonably want to cache (e.g., text type files).
  44. :param pelican: The Pelican instance
  45. '''
  46. for dirpath, _, filenames in os.walk(pelican.settings['OUTPUT_PATH']):
  47. for name in filenames:
  48. if should_compress(name):
  49. filepath = os.path.join(dirpath, name)
  50. create_gzip_file(filepath, should_overwrite(pelican.settings))
  51. def should_compress(filename):
  52. '''Check if the filename is a type of file that should be compressed.
  53. :param filename: A file name to check against
  54. '''
  55. for extension in EXCLUDE_TYPES:
  56. if filename.endswith(extension):
  57. return False
  58. return True
  59. def should_overwrite(settings):
  60. '''Check if the gzipped files should overwrite the originals.
  61. :param settings: The pelican instance settings
  62. '''
  63. return settings.get('GZIP_CACHE_OVERWRITE', False)
  64. def create_gzip_file(filepath, overwrite):
  65. '''Create a gzipped file in the same directory with a filepath.gz name.
  66. :param filepath: A file to compress
  67. :param overwrite: Whether the original file should be overwritten
  68. '''
  69. compressed_path = filepath + '.gz'
  70. with open(filepath, 'rb') as uncompressed:
  71. gzip_compress_obj = zlib.compressobj(COMPRESSION_LEVEL,
  72. zlib.DEFLATED, WBITS)
  73. uncompressed_data = uncompressed.read()
  74. gzipped_data = gzip_compress_obj.compress(uncompressed_data)
  75. gzipped_data += gzip_compress_obj.flush()
  76. with open(compressed_path, 'wb') as compressed:
  77. logger.debug('Compressing: %s' % filepath)
  78. try:
  79. compressed.write(gzipped_data)
  80. except Exception as ex:
  81. logger.critical('Gzip compression failed: %s' % ex)
  82. if overwrite:
  83. logger.debug('Overwriting: %s with %s' % (filepath, compressed_path))
  84. os.remove(filepath)
  85. os.rename(compressed_path, filepath)
  86. def register():
  87. signals.finalized.connect(create_gzip_cache)