【发布时间】:2019-01-07 20:49:06
【问题描述】:
我试图允许用户从我的烧瓶应用程序下载 csv 文件,但在处理从运行 Apache2 的 ubuntu 18 服务器下载文件的路径中。
import flask
import os
from io import BytesIO
basedir = os.path.abspath(os.path.dirname(__file__))
app = flask.Flask(__name__)
app.config["DEBUG"] = True
@app.route('/<string:report>/<string:action>', methods=['GET'])
def report(report,action):
if action == 'download':
files = os.listdir(os.path.join(basedir, f'static/reports/{report}'))
filepath = url_for(f'static/reports/{report}/{files[-1]}')
output = BytesIO()
with open(filepath, 'rb') as f:
data = f.read()
output.write(data)
output.seek(0)
return send_file(output,attachment_filename=files[-1], as_attachment=True)
但我收到此错误:[Errno 2] No such file or directory: '/static/reports'
我的 Apache2 配置已经有静态文件的别名 像这样:
Alias /static /var/www/FlaskApp/FlaskApp/static
<Directory /var/www/FlaskApp/FlaskApp/static/>
Order allow,deny
Allow from all
</Directory>
我也尝试在静态下为我的报告文件夹创建一个别名,但我仍然得到相同的结果。
我有什么明显的遗漏吗?
【问题讨论】:
-
为什么要将数据读入
BytesIO()对象?send_file()将接受filepath直接,并更有效地启动文件。 -
或者使用
send_from_directory(),它需要一个目录和文件名。