Skip to content

Instantly share code, notes, and snippets.

@jwineinger
Created December 16, 2011 16:46
Show Gist options
  • Save jwineinger/1486815 to your computer and use it in GitHub Desktop.
Save jwineinger/1486815 to your computer and use it in GitHub Desktop.
Django staticfiles JS-minifying storage backend
from django.core.files.storage import FileSystemStorage
from slimit import minify
class StaticFileStorageAndJSMinifier(FileSystemStorage):
"""
A storage backend to be used by the staticfiles app -- STATICFILES_STORAGE
setting. This backend operates just as a normal filesystem storage backend
except when it detects a javascript file.
After a javascript file is saved, we reopen the file, minify the contents
and write back to the same place. This allows the default storage
behaviors for finding an unused path to work as defined in core.
Only works in Django > 1.3 where the collectstatic management command
actually uses the storage backend to save the file. In Django 1.3,
collectstatic uses a filesystem copy for local storages, which bypasses
the storage backend so we cannot hook into it to modify the files.
"""
def _minify_js(self, path):
f = open(path, 'r+b')
js_content = f.read()
js_minified = minify(js_content)
f.rewind()
f.write(js_minified)
f.close()
def _save(self, name, content):
name = super(StaticFileStorageAndJSMinifier, self)._save(name, content)
if name.endswith('js'):
full_path = self.path(name)
self._minify_js(full_path)
return name
@roidelapluie
Copy link

@jwineinger What is the license of this gist?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment