Prepend the minified static file header using a custom Storage class

(imported from commit 2b67a6d94de1693bdb8a91f455b92375692f4c41)
This commit is contained in:
Zev Benjamin 2013-06-11 18:01:13 -04:00
parent 19d8cfd657
commit 33fed064e2
4 changed files with 61 additions and 11 deletions

View File

@ -222,8 +222,9 @@ STATICFILES_FINDERS = (
if DEBUG:
STATICFILES_STORAGE = 'pipeline.storage.PipelineStorage'
else:
STATICFILES_STORAGE = 'pipeline.storage.PipelineCachedStorage'
STATICFILES_STORAGE = 'zephyr.storage.HumbugStorage'
STATIC_HEADER_FILE = 'zephyr/static_header.txt'
STATIC_ROOT = 'prod-static/collected'
# This is the default behavior from Pipeline, but we set it

View File

@ -4,11 +4,6 @@
cd "$(dirname "$0")"/..
if ! which sponge >/dev/null; then
echo 'Install the moreutils package.' >&2
exit 1
fi
# Redirect output to a log file (most recent run only)
exec >update-prod-static.log
@ -32,11 +27,6 @@ rm -rf prod-static/serve-new
mkdir -p prod-static/serve-new
cp -r prod-static/collected/{favicon.ico,robots.txt,html,images,third,min,audio} prod-static/serve-new/
# Prepend the third-party code notice to JavaScript and CSS files.
for f in prod-static/serve-new/min/*.{js,css}; do
cat zephyr/static/header.txt $f | sponge $f
done
# Sync the new directory to the one nginx actually serves.
# Hopefully this doesn't race too badly for clients loading
# right as a deploy happens.

59
zephyr/storage.py Normal file
View File

@ -0,0 +1,59 @@
from django.conf import settings
from django.contrib.staticfiles.storage import CachedFilesMixin, StaticFilesStorage
from pipeline.storage import PipelineMixin
import os.path
class AddHeaderMixin(object):
def post_process(self, paths, dry_run=False, **kwargs):
if dry_run:
return
with open(settings.STATIC_HEADER_FILE) as header_file:
header = header_file.read().decode(settings.FILE_CHARSET)
# A dictionary of path to tuples of (old_path, new_path,
# processed). The return value of this method is the values
# of this dictionary
ret_dict = {}
for name in paths:
storage, path = paths[name]
# Find the top-level directory for the file
head, _ = os.path.split(path)
top_dir = head
while head != '':
top_dir = head
head, _ = os.path.split(head)
if top_dir != 'min':
ret_dict[path] = (path, path, False)
continue
# Prepend the header
with storage.open(path) as orig_file:
orig_contents = orig_file.read().decode(settings.FILE_CHARSET)
storage.delete(path)
with storage.open(path, 'w') as new_file:
new_file.write(header + orig_contents)
ret_dict[path] = (path, path, True)
super_class = super(AddHeaderMixin, self)
if hasattr(super_class, 'post_process'):
super_ret = super_class.post_process(paths, dry_run, **kwargs)
else:
super_ret = []
# Merge super class's return value with ours
for val in super_ret:
old_path, new_path, processed = val
if processed:
ret_dict[old_path] = val
return ret_dict.itervalues()
class HumbugStorage(PipelineMixin, AddHeaderMixin, CachedFilesMixin, StaticFilesStorage):
pass