Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I download a file from a user-provided URL in Flask? [duplicate]

Tags:

python

flask

I want to get a URL from the user in my Flask application, then download and save that URL to disk.

like image 223
MonadMania Avatar asked Feb 03 '26 05:02

MonadMania


2 Answers

Using requests, 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)
like image 180
davidism Avatar answered Feb 04 '26 18:02

davidism


I always use the following. It depends on the target file on how you process it, of course. In my case it is an icalender file.

from urllib.request import urlopen
//I used python3

location = 'http://ical.citesi.nl/?icalguid=81b4676a-b3c0-4b4c-89bd-d91c3a52fa7d&1511210388789'
result = urlopen(location)
like image 35
Fthi.a.Abadi Avatar answered Feb 04 '26 19:02

Fthi.a.Abadi