Reliably create a Django File using the contents of a URL

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# The file reference must be populated with a django.core.files.File instance
# but File cannot handle file-like objects such as those returned by urlopen -
# see http://code.djangoproject.com/ticket/8501
#
# Since we'd like to get the normal file name collision avoidance, automatic
# location handling, etc. we'll create a django NamedTemporaryFile because the
# default file storage save logic is smart enough to simply move the temporary
# file to the correct location.
 
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))

More like this

  1. Effective content caching for mass-load site using redirect feature by nnseva 2 years, 9 months ago
  2. Upgrade django url tags by Craterdome 1 year ago
  3. Jquery ajax csrf framework for Django by chriszweber 2 years, 3 months ago
  4. Database file storage by powerfox 5 years, 2 months ago
  5. Convert LaTeX templates to various output formats by blizz 7 years, 1 month ago

Comments

fish2000 (on March 31, 2010):

FYI, using 'delete=True' throws a TypeError under Django 1.1.1 -- NamedTemporaryFile's constructor doesn't expect the keyword.

Take it out and it works fine; great trick otherwise, thanks

#

clawlor (on March 16, 2012):

Don't forget that File.save() does not delete any existing data. Use File.delete() if need be.

#

(Forgotten your password?)