Skip to content

Instantly share code, notes, and snippets.

@hcarvalhoalves
Created November 7, 2012 22:44
Show Gist options
  • Save hcarvalhoalves/4035045 to your computer and use it in GitHub Desktop.
Save hcarvalhoalves/4035045 to your computer and use it in GitHub Desktop.
File storage for development server
from django.core.files.base import ContentFile
from django.core.files.storage import FileSystemStorage
from django.utils.encoding import filepath_to_uri
from django.utils.log import getLogger
from django.conf import settings
from urllib2 import urlopen, HTTPError
from urlparse import urljoin
logger = getLogger(__name__)
class FallbackStorage(FileSystemStorage):
"""
A storage that will download files from a remote location when the file
doesn't exist locally. Useful for downloading assets from your production
server from your development server on demand.
"""
def __init__(self, *args, **kwargs):
self.fallback_url = getattr(settings, 'FALLBACK_STORAGE_URL', '/')
super(FallbackStorage, self).__init__(*args, **kwargs)
def _fetch(self, name):
url = urljoin(self.fallback_url, filepath_to_uri(name))
try:
content = ContentFile(urlopen(url).read())
self._save(name, content)
except HTTPError:
logger.warning('Failed fetching %s' % name)
return False
return True
def url(self, name):
if not self.exists(name):
self._fetch(name)
return super(FallbackStorage, self).url(name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment