Advertisement
noelph

s3utils

May 21st, 2013
183
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.37 KB | None | 0 0
  1. ########################################
  2. # s3utils.py
  3. ########################################
  4.  
  5. import os
  6. from os.path import splitext
  7. from django.core.files.base import File
  8. from django.core.files.storage import get_storage_class
  9. from storages.backends.s3boto import S3BotoStorage
  10.  
  11.  
  12. class CachedS3BotoStorage(S3BotoStorage):
  13.     """
  14.    S3 storage backend that saves the files locally, too.
  15.    """
  16.     def __init__(self, *args, **kwargs):
  17.         super(CachedS3BotoStorage, self).__init__(*args, **kwargs)
  18.         self.local_storage = get_storage_class("compressor.storage.CompressorFileStorage")()
  19.  
  20.     def save(self, name, content):
  21.         name = super(CachedS3BotoStorage, self).save(name, content)
  22.         self.local_storage._save(name, content)
  23.         return name
  24.    
  25. class StaticToS3Storage(S3BotoStorage):
  26.     '''From Matt as described here:
  27.    http://stackoverflow.com/questions/8688815/django-compressor-how-to-write-to-s3-read-from-cloudfront
  28.    
  29.    Requires django-storages that has "rewind=True" as implemented here:
  30.    https://github.com/iserko/django-storages
  31.    '''
  32.     def __init__(self, *args, **kwargs):
  33.         super(StaticToS3Storage, self).__init__(*args, **kwargs)
  34.         self.local_storage = get_storage_class("compressor.storage.CompressorFileStorage")()
  35.    
  36.     def save(self, name, content):
  37.         ext = splitext(name)[1]
  38.         parent_dir = name.split('/')[0]
  39.         if ext in ['.css', '.js'] and not parent_dir == 'admin':
  40.             self.local_storage._save(name, content)
  41.             gzip = self.gzip
  42.             self.gzip = False  # upload to S3 but don't compress
  43.             filename = super(StaticToS3Storage, self).save(name, content)
  44.             self.gzip = gzip  # revert to original value
  45.         else:
  46.             filename = super(StaticToS3Storage, self).save(name, content)
  47.             return filename
  48.  
  49.  
  50. StaticS3BotoStorage = lambda: StaticToS3Storage(location='static')
  51. MediaS3BotoStorage = lambda: S3BotoStorage(location='media')
  52. CompressedS3BotoStorage = lambda: CachedS3BotoStorage(location='static')
  53.  
  54.  
  55. ##################################
  56. # settings.py
  57. ##################################
  58.  
  59. DEFAULT_FILE_STORAGE = 's3utils.MediaS3BotoStorage'
  60. STATICFILES_STORAGE = 's3utils.StaticS3BotoStorage'
  61. COMPRESS_STORAGE = 's3utils.CompressedS3BotoStorage'
  62.  
  63. COMPRESS_OUTPUT_DIR = 'compressed/' + SITE_NAME
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement