Login

Tag "urlopen"

Snippet List

Reliably create a Django File using the contents of a URL

There's no direct way to save the contents of a URL to a Django File field: you're required to use a File instance but those can only safely wrap normal files, not the file-like object returned by urllib2.urlopen. Several examples online use urllib.urlretrieve() which creates a temporary file but performs no error handling without writing a ton of hackish code. This demonstrates how to create a NamedTemporaryFile, fill it with the URL contents and save it, all using APIs which raise exceptions on errors.

  • url
  • filefield
  • file
  • urlopen
Read More

1 snippet posted so far.