Skip to content

Instantly share code, notes, and snippets.

@luish
Last active December 20, 2015 11:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luish/6127082 to your computer and use it in GitHub Desktop.
Save luish/6127082 to your computer and use it in GitHub Desktop.
Django: save an image from URL (works on Amazon S3)
from django.core.files.storage import default_storage
from django.core.files.base import ContentFile
import os
import uuid
import urllib
def save_image_from_url(url):
path = 'uploads/'
try:
filename = os.path.basename(url)
extension = os.path.splitext(filename)[1]
format = uuid.uuid1().hex + extension
path = os.path.join(path, format)
f = urllib.urlopen(url)
saved = default_storage.save(path, ContentFile(f.read()))
return saved
except IOError, e:
print e
# Set the default file storage.
# If you're using Amazon S3:
DEFAULT_FILE_STORAGE = 'storages.backends.s3boto.S3BotoStorage'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment