gzip_cache.py 3.3 KB

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