gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 22:06:29 26 4
gpt4 key购买 nike

我正在尝试使用我在以下网址找到的代码:http://code.runnable.com/UiIdhKohv5JQAAB6/how-to-download-a-file-generated-on-the-fly-in-flask-for-python

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

所以我写了下面的代码:

@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)

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

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 包更新到最新版本但没有成功。

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

提前致谢

最佳答案

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

from flask import send_file

@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)

关于python - 从基于 Flask 的 Python 服务器下载文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37937091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com