使用 Flask,如何从用户给定的 URL 下载文件? [英] Using Flask, how can I download a file from a user-given URL?
问题描述
我正在使用 Flask 在运行 Python 3.3 盒式磁带的 OpenShift 服务器上编写(应该是什么)快速应用程序.这是我想要的:
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:
我需要一个 Flask 方法来从 URL 获取文件并将该文件保存到磁盘.
I need a Flask method for getting a file from a URL and saving that file to disk.
我应该澄清一下,我对网络应用程序的经验很少.尽管进行了数小时的阅读和搜索,我还是无法掌握 URL 和文件传输的窍门.
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.
推荐答案
使用 requests,以下是下载和保存 Google 徽标的方法:
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)
您可以在 Flask 视图中使用它来下载用户提供的 URL.
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)
这篇关于使用 Flask,如何从用户给定的 URL 下载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!