使用Flask,如何从用户指定的URL下载文件?

时间:2014-07-22 14:47:01

标签: python flask openshift

我正在编写(应该是什么)在运行带有Flask的Python 3.3盒式磁带的OpenShift服务器上的快速应用程序。这就是我想要的:

我需要一个Flask方法从URL获取文件并将该文件保存到磁盘。

编辑:我应该澄清,我几乎没有网络应用程序的经验。尽管经过数小时的阅读和搜索,我仍无法掌握URL和文件传输。

2 个答案:

答案 0 :(得分:6)

使用requests,以下是如何下载和保存Google徽标的信息:

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。

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)

答案 1 :(得分:0)

我总是使用以下内容。当然,这取决于你如何处理它的目标文件。就我而言,它是一个icalender文件。

Sub Data_scraper()
    Dim IE As New InternetExplorer
    Dim ieDoc As HTMLDocument

    With IE
        .Visible = False
        .navigate "http://www.retailbusinesstechnologyexpo.com/exhibitor-profile/citizen-systems-europe"
        Do Until .readyState = 4: DoEvents: Loop
        Set ieDoc = .document
        MsgBox ieDoc.getElementsByClassName("editorLabel")(0).innerText
    End With
    IE.Quit
End Sub