简体   繁体   English

从 web 下载文件到 flask 服务器

[英]download file FROM web TO flask server

My flask app should download files from urls which are posted to my app by a json object.我的 flask 应用程序应该从由 json object 发布到我的应用程序的 url 下载文件。 The files should be downloaded for further processing.应下载文件以供进一步处理。 I do not get an error message.我没有收到错误消息。 A lot of tutorials are about how a user uploads a file, but this is not my case.很多教程都是关于用户如何上传文件的,但这不是我的情况。 Can anyone help?任何人都可以帮忙吗?

import os


from flask import Flask, request, jsonify
import urllib.request as web

app = Flask(__name__)
download_folder=os.path.join(app.instance_path,'downloads')
app.config['DOWNLOAD_FOLDER'] = download_folder


@app.route('/syncaudio', methods=['POST'])
def syncaudio():
    files = request.get_json(force=True)

    for file_url in files['syncFileUrls']:
        local_file = os.path.join(app.config['DOWNLOAD_FOLDER'], file_url.rsplit('/')[-1])
        web.urlretrieve(file_url, local_file)


if __name__ == '__main__':
    app.run(debug=True)

urlretrieve(file_url,local_file) is the right way of doing it, there is nothing specific to Flask. urlretrieve(file_url,local_file)是正确的方法,Flask 没有什么特别的。

I suggest you to try in a Python interpreter to see if that works:我建议您尝试使用 Python 解释器,看看是否可行:

>>> import urllib.request
>>> urllib.request.urlretrieve('http://some/url', '/some/file/location.txt')

If that works, this means your code is never getting executed.如果可行,这意味着您的代码永远不会被执行。

You may want to print the value of files to see if the list is not empty.您可能希望打印files的值以查看列表是否为空。

I found the solution!我找到了解决方案!

for downloading FROM web TO flask server I do not need to create a folder like this:从 web 下载到 flask 服务器我不需要创建这样的文件夹:

download_folder=os.path.join(app.instance_path,'downloads') app.config['DOWNLOAD_FOLDER'] = download_folder

I just have to create a download folder via:我只需要通过以下方式创建一个下载文件夹:

os.makedirs('downloads')

really simpel:)真的很简单:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM