-
-
Save btimby/1870959 to your computer and use it in GitHub Desktop.
Django staticfiles JS-minifying storage backend
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import os.path | |
from django.core.files.storage import FileSystemStorage | |
from django.core.files.base import ContentFile | |
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, content): | |
return ContentFile(minify(content.read())) | |
def _save(self, name, content): | |
# TODO: minify css also! | |
if os.path.splitext(name)[1] == '.js': | |
try: | |
content = self._minify_js(content) | |
except: | |
pass # Leave content untouched | |
return super(StaticFileStorageAndJSMinifier, self)._save(name, content) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This fork has the benefit of not writing, reading, then re-writing the file contents. Also, since it does no writing directly, it can be adapted to a mixin that would work with other storage backends (like S3Storage).