Skip to content

Instantly share code, notes, and snippets.

@dsanders11
Created June 13, 2015 04:26
Show Gist options
  • Select an option

  • Save dsanders11/41ba66caadb5be81dd53 to your computer and use it in GitHub Desktop.

Select an option

Save dsanders11/41ba66caadb5be81dd53 to your computer and use it in GitHub Desktop.
File storage backend for Django which adds the file contents hash to the filename (like CachedStaticFilesStorage)
import os
try:
# Django 1.7+
from django.contrib.staticfiles.storage import HashedFilesMixin
except:
from django.contrib.staticfiles.storage import (
CachedFilesMixin as HashedFilesMixin)
from django.core.files.storage import FileSystemStorage
class HashedFileSystemStorage(FileSystemStorage, HashedFilesMixin):
""" File storage backend which adds the MD5 hash to file names """
def _save(self, name, content):
path, filename = os.path.split(name)
root, ext = os.path.splitext(filename)
file_hash = self.file_hash(filename, content)
if file_hash is not None:
file_hash = ".%s" % file_hash
hashed_name = os.path.join(path, "%s%s%s" % (root, file_hash, ext))
return super(HashedFileSystemStorage, self)._save(hashed_name, content)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment