Using Flask, how can I download a file from a user-given URL?
Question: I'm writing (what was supposed to be) a quick application on an OpenShift
server running a Python 3.3 cartridge with Flask. Here's what I want:

I need a Flask method for getting a file from a URL and saving that file to
disk.

edit: I should clarify, I have little experience web apps. Despite hours of
reading and searching, I can't get the hang of URLs and file transfers.


Answer: Using [requests](http://docs.python-requests.org/en/latest/), here's how to
download and save the Google logo:

    
    
    import requests
    
    r = requests.get('https://www.google.com/images/srpr/logo11w.png')
    
    with open('google_logo.png', 'wb') as f:
        f.write(r.content)
    

You can use this from within a Flask view to download a user provided URL.

    
    
    from flask import request
    import requests
    
    
    @app.route('/user_download')
    def user_download():
        url = request.args['url']  # user provides url in query string
        r = requests.get(url)
    
        # write to a file in the app's instance folder
        # come up with a better file name
        with app.open_instance_resource('downloaded_file', 'wb') as f:
            f.write(r.content)
    

