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

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

本文介绍了从基于Flask的Python服务器下载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使我在此URL上找到的代码成为工作: http://code.runnable.com/UiIdhKohv5JQAAB6/how-to-download-a-file-generate-on-the-fly-in- flask-for-python

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

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

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.

所以我写了以下代码:

@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

我将Flask和Werkzeug软件包更新为最新版本,但没有成功.

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

如果有人有一个主意,那就太好了.

If anybody have an idea it would be great.

预先感谢

推荐答案

解决此问题的最佳方法是使用已经预定义的帮助器功能 send_file() 在烧瓶中:

The best way to solve this issue is to use the already predefined helper function send_file() in 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)

这篇关于从基于Flask的Python服务器下载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-28 11:20