使用烧瓶应用程序在HTML上'Download simulation data'链接



我正在读取用户输入并发送它们进行处理。处理后,将显示结果。除了结果,我还希望在网页上有一个链接,以便能够将数据下载为csv文件。我处理输入的函数如下所示。

@app.route('/process', methods=['POST'])
def process_data():
# create csv_file
return render_template("results.html", data=csv_file)

结果.html有以下行。

<p><a href="{{ url_for('download', filename=data) }}"> <large>Download simulation data </large></a></p>

此链接正确显示在网页上。我下载数据的函数如下所示。

@app.route('/download/<filename>')
def download(filename):
response = make_response(filename)
response.headers["Content-Disposition"] = "attachment; filename=Simulation.csv"
response.headers["Content-Type"] = "text/csv"
return response

单击下载链接,我得到"414 请求 URI 太大"。

有没有更好的解决方案将数据从烧瓶传递到html再传递烧瓶? 我可以看到我的整个数据都附加到 url,我可以以某种方式避免这种情况吗? 是否可以在渲染结果时直接传递响应.html并使其可下载?

更新

我了解到将数据放在 url 中是一个坏主意。相反,我可以通过对数据进行编码来使用dataurl,然后在html的href标签中使用csv的数据url。

buffer = StringIO()
dataframe.to_csv(buffer, index=False)
buffer.seek(0)
data_str = base64.b64encode(buffer.getvalue().encode('utf8')).decode('ascii')
url = "data:text/csv; base64,{}".format(data_str)

HTML 如下所示。

<a download="SSW_Simulation.csv" href="{{ data_url }}">download</a>

但是,我猜此解决方案在IE浏览器中不起作用,因为不支持数据的URL。我应该将 csv 文件保存在某个地方并将该文件名传递给 html 吗?以便在出现提示时,我可以从临时位置获取它并使用make_response下载?我不想将文件保存到磁盘。

在javascript中处理数据解决了@Jeronimo建议的问题。 json字符串被传递给html页面。

import json
@app.route('/process', methods=['POST'])
def process_data():
# create csv_file
data = json.dumps(csv_file)
return render_template("results.html", data=data)

这个答案中建议的Javascript被添加到html和下载按钮中。

<button onclick="download({{ data }}, 'myfile.csv', 'text/csv')">download data</button>

最新更新