You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python读取HTML文件转为字符串变量供Flask调用的最简方法

读取本地HTML文件内容为Python字符串的实现方案

你可以直接通过Python内置的文件读取方法读取生成的./templates/backtest.html文件,具体代码如下:

# 执行回测生成文件的原有代码
p = BacktraderPlotting(style='bar',barup='green',volume=False, lookback=200, filename="./templates/backtest.html", output_mode='save')

# 新增读取文件逻辑
html_file_path = "./templates/backtest.html"
with open(html_file_path, "r", encoding="utf-8") as file:
    # backtest_html_str 就是你需要的HTML内容字符串,可直接传入Flask视图
    backtest_html_str = file.read()

补充注意点

  • 需确保读取操作在回测文件生成完成后执行,避免读取到空内容或者触发文件不存在报错
  • 如果需要兼容文件未生成的场景,可以增加异常捕获逻辑:
try:
    with open(html_file_path, "r", encoding="utf-8") as file:
        backtest_html_str = file.read()
except FileNotFoundError:
    backtest_html_str = "<p>暂无回测结果,请先运行回测程序</p>"
  • 前端渲染HTML字符串时,需要在Jinja2模板中添加safe过滤器,避免HTML标签被自动转义:
<!-- 模态框内容部分示例 -->
<div class="modal-body">
  {{ backtest_html_str|safe }}
</div>

内容的提问来源于stack exchange,提问作者Will Powers

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.12 00:03:03