/secdownload_storage/__init__.py

https://bitbucket.org/ionelmc/django-secdownload-storage · Python · 29 lines · 24 code · 5 blank · 0 comment · 5 complexity · f77fc5c6eeeee3218ddf9c8a0e72acd6 MD5 · raw file

  1. import time
  2. import hashlib
  3. import urlparse
  4. from django.core.files.storage import FileSystemStorage, filepath_to_uri
  5. from django.conf import settings
  6. from django.core.exceptions import ImproperlyConfigured
  7. ENABLED = settings.SEC_DOWNLOAD_ENABLED
  8. class SecDownloadFileSystemStorage(FileSystemStorage):
  9. def __init__(self, location=None, base_url=None, secret_key=None):
  10. if ENABLED:
  11. if base_url is None:
  12. base_url = settings.SEC_DOWNLOAD_MEDIA_URL
  13. if secret_key is None:
  14. secret_key = settings.SEC_DOWNLOAD_SECRET_KEY
  15. self.secret_key = secret_key
  16. super(self.__class__, self).__init__(location=location, base_url=base_url)
  17. def url(self, name):
  18. if ENABLED:
  19. file_path = filepath_to_uri(name)
  20. hextime = "%08x" % time.time()
  21. token = hashlib.md5(self.secret_key + '/' + file_path + hextime).hexdigest()
  22. return urlparse.urljoin(self.base_url, '/'.join((token, hextime, file_path)))
  23. else:
  24. return super(self.__class__, self).url(name)