I want to get a URL from the user in my Flask application, then download and save that URL to disk.
Asked
Active
Viewed 1.1k times
2
-
There are no Flask-specific methods for that, because any normal Python method to download a file from a URL will do that for you. – Martijn Pieters Jul 22 '14 at 14:48
2 Answers
8
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)

davidism
- 121,510
- 29
- 395
- 339
1
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)

Fthi.a.Abadi
- 324
- 2
- 8