Skip to content

Instantly share code, notes, and snippets.

@btimby
Forked from jwineinger/storage.py
Created February 20, 2012 19:43
Show Gist options
  • Save btimby/1870959 to your computer and use it in GitHub Desktop.
Save btimby/1870959 to your computer and use it in GitHub Desktop.
Django staticfiles JS-minifying storage backend
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)
@btimby
Copy link
Author

btimby commented Feb 20, 2012

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).

@roidelapluie
Copy link

@btimby 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