从基于 Flask 的 Python 服务器下载文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37937091/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:07:10  来源:igfitidea点击:

Download a file from a Flask-based Python server

pythonflaskwerkzeugwebclient-download

提问by Alexandre D.

I'm trying to make work a code that I found at this URL: http://code.runnable.com/UiIdhKohv5JQAAB6/how-to-download-a-file-generated-on-the-fly-in-flask-for-python

我正在尝试使用我在此 URL 上找到的代码:http: //code.runnable.com/UiIdhKohv5JQAAB6/how-to-download-a-file-generated-on-the-fly-in-flask-蟒蛇

My goal is to be able to download a file on a web browser when the user access to a web service on my Flask-base Python server.

我的目标是当用户访问基于 Flask 的 Python 服务器上的 Web 服务时,能够在 Web 浏览器上下载文件。

So I wrote the following code:

所以我写了下面的代码:

@app.route("/api/downloadlogfile/<path>")
def DownloadLogFile (path = None):
    if path is None:
        self.Error(400)

    try:
        with open(path, 'r') as f:
            response  = make_response(f.read())
        response.headers["Content-Disposition"] = "attachment; filename=%s" % path.split("/")[2]

        return response
    except Exception as e:
        self.log.exception(e)
        self.Error(400)

But this code doesn't seem to work. Indeed I get an error that I didn't manage to fix:

但是这段代码似乎不起作用。事实上,我收到了一个我无法修复的错误:

Traceback (most recent call last):
File "C:\Python27\lib\site-packages\gevent\pywsgi.py", line 508, in handle_one_response
self.run_application()
File "C:\Python27\lib\site-packages\geventwebsocket\handler.py", line 88, in run_application
return super(WebSocketHandler, self).run_application()
File "C:\Python27\lib\site-packages\gevent\pywsgi.py", line 495, in run_application
self.process_result()
File "C:\Python27\lib\site-packages\gevent\pywsgi.py", line 484, in process_result
for data in self.result:
File "C:\Python27\lib\site-packages\werkzeug\wsgi.py", line 703, in __next__
return self._next()
File "C:\Python27\lib\site-packages\werkzeug\wrappers.py", line 81, in _iter_encoded
for item in iterable:
TypeError: 'Response' object is not iterable

I update my Flask and Werkzeug package to the last version but without success.

我将 Flask 和 Werkzeug 包更新到最新版本,但没有成功。

If anybody have an idea it would be great.

如果有人有想法,那就太好了。

Thanks in advance

提前致谢

回答by K DawG

The best way to solve this issue is to use the already predefined helper function send_file()in flask:

解决这个问题的最好方法是使用send_file()flask中已经预定义好的辅助函数:

@app.route("/api/downloadlogfile/<path>")
def DownloadLogFile (path = None):
    if path is None:
        self.Error(400)
    try:
        return send_file(path, as_attachment=True)
    except Exception as e:
        self.log.exception(e)
        self.Error(400)