Created
June 13, 2015 04:26
-
-
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)
This file contains hidden or 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 | |
| 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