Jan 26
Django: reliably saving URLs to a file field
In the hopes that this saves someone else the hassle, I recently ran into a bit of an inconvenience while importing remote URLs into Django ImageFields. It's easy to work with local files - simply wrap them in django.core.files.File() objects - but File can't handle the file-like objects returned by urlopen (see http://code.djangoproject.com/ticket/8501) which don't implement all of the methods supported by a normal file.
Most of the suggestions you'll find online suggest using urllib.urlretrieve to save the remote URL to a temporary file which you can then wrap normally. Unfortunately, urlretrieve does no error handling by default and it's a bit contorted to add so I found it easier to use Django's NamedTemporaryFile class:
Most of the suggestions you'll find online suggest using urllib.urlretrieve to save the remote URL to a temporary file which you can then wrap normally. Unfortunately, urlretrieve does no error handling by default and it's a bit contorted to add so I found it easier to use Django's NamedTemporaryFile class:
from django.core.files import File from django.core.files.temp import NamedTemporaryFile img_temp = NamedTemporaryFile(delete=True) img_temp.write(urllib2.urlopen(url).read()) img_temp.flush() im.file.save(img_filename, File(img_temp))


blog comments powered by Disqus