gzip_cache.py 3.0 KB

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