首页 > 解决方案 > python flask render_template 并将 csv/excel 返回到浏览器

问题描述

我正在创建一个以 CSV 作为输入的烧瓶应用程序。解析 CSV 和内容。然后将更新的 CSV 返回到浏览器以下载/或立即下载。该程序需要一个 HTML 模板供用户交互。我正在尝试使用 render_template() 方法通过烧瓶返回 HTML 文件和 CSV 文件。实现这一目标的最佳方法是什么?

@app.route("/", methods=["GET", "POST"])
def index():
        if request.method == "POST":
    print("POST request received!")

    if "file" not in request.files:
        return redirect(request.url)

    list_keywords = request.files["file"]
    if not list_keywords:
        return "No file"
    the_list = io.StringIO(list_keywords.stream.read().decode("UTF8"), newline=None)
    csv_input = csv.reader(the_list)
    ...# rest of program.....
    csv_file1 = pd.DataFrame(internal_linking_opportunities,
                                     columns=["Keyword", "Text", "Source URL", "Target URL", "Link Presence", "Keyword Position"])

si = io.StringIO()
cw = csv.writer(csv_file1)
output = make_response(si.getvalue())
output.headers["Content-Disposition"] = "attachment; filename=export.csv"
output.headers["Content-type"] = "text/csv"


return Response(render_template('index.html', output=output))

我尝试使用其他方法返回 CSV,但没有成功。开始认为这可能是由于我正在使用的 render_template 函数。感谢您的帮助。

标签: pythoncsvflask

解决方案


的第二个参数render_template被调用context,可用于为模板提供一些用于渲染的变量。将Response对象添加到模板上下文不会返回 that Response,而是使该Response对象可从模板中访问。

Flask 有一个专门的方法将文件发送回浏览器:

https://flask.palletsprojects.com/en/1.1.x/api/#flask.send_file

您的退货声明可能如下所示:

return send_file(file_pointer, as_attachment=True, attachment_filename="export.csv")

除了提供文件指针作为第一个参数,您还可以通过提供该文件的路径来使用本地磁盘中的文件。如果您提供文件指针,请确保将其设置为文件的开头。


推荐阅读