gzip_cache.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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. try:
  57. logger.debug('Compressing: %s' % filepath)
  58. compressed = gzip.open(compressed_path, 'wb')
  59. compressed.writelines(uncompressed)
  60. except Exception as ex:
  61. logger.critical('Gzip compression failed: %s' % ex)
  62. finally:
  63. compressed.close()
  64. def register():
  65. signals.finalized.connect(create_gzip_cache)