2

I want to have a user input a file URL and then have my django app download the file from the internet.

My first instinct was to call wget inside my django app, but then I thought there may be another way to get this done. I couldn't find anything when I searched. Is there a more django way to do this?

Joff
  • 11,247
  • 16
  • 60
  • 103
  • http://stackoverflow.com/questions/38508715/python-download-images-with-alernating-variables/38510385#38510385 – Fhaab Jul 21 '16 at 23:29
  • You should be _very_ careful with downloading whatever the user specifies. The `REQUESTS` library can handle it: http://docs.python-requests.org/en/master/user/quickstart/#raw-response-content – Nick Jul 21 '16 at 23:29
  • 1
    Possible duplicate of [How do I download a file over HTTP using Python?](http://stackoverflow.com/questions/22676/how-do-i-download-a-file-over-http-using-python) – rafalmp Jul 21 '16 at 23:33

2 Answers2

4

You are not really dependent on Django for this. I happen to like using requests library.
Here is an example:

    import requests

    def download(url, path, chunk=2048):
        req = requests.get(url, stream=True)
        if req.status_code == 200:
            with open(path, 'wb') as f:
                for chunk in req.iter_content(chunk):
                    f.write(chunk)
                f.close()
            return path
        raise Exception('Given url is return status code:{}'.format(req.status_code))

Place this is a file and import into your module whenever you need it.
Of course this is very minimal but this will get you started.

Justin M. Ucar
  • 853
  • 9
  • 17
  • cool, just wanted to know if I should reach into a plain python library or if there was a djangified way to do it – Joff Jul 22 '16 at 00:08
  • in this, it will save the file in local but I don't want to save the file locally it should be available for download directly to a user – Deepak Chawla Nov 30 '19 at 10:08
1

You can use urlopen from urllib2 like in this example:

import urllib2
pdf_file = urllib2.urlopen("http://www.example.com/files/some_file.pdf")
with open('test.pdf','wb') as output:
    output.write(pdf_file.read())

For more information, read the urllib2 docs.

pazitos10
  • 1,641
  • 16
  • 25