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

Flask传递图片src至HTML失败求助:TSP可视化图无法显示

解决TSP Web应用中Matplotlib图表无法显示的问题

核心问题

直接传递本地文件路径给HTML的img标签,Flask无法正确映射到静态资源路由,导致浏览器无法加载图片。


具体解决方案

1. 使用Flask的url_for生成合法静态资源URL

修改路由代码,用url_for生成Flask认可的静态资源访问路径,替代硬编码的本地路径:

from flask import url_for

# ... 你的绘图代码保持不变 ...
plt.savefig("static/pictures/aco.png")

# 生成正确的静态资源URL
plot_url = url_for('static', filename='pictures/aco.png')
return render_template(
    "calculator.html", 
    num_points=num_points, 
    max_iter=max_iter, 
    size_pop=size_pop, 
    prob_mut=prob_mut, 
    plot_url=plot_url
)

HTML代码无需修改,因为plot_url现在是浏览器可直接访问的完整路由。

2. 验证静态文件夹结构与权限

  • 确认项目根目录下存在static/pictures目录,若缺失则手动创建:
    mkdir -p static/pictures
    
  • 检查Flask进程是否有该目录的写入权限,避免图片保存失败。可添加保存后校验:
    import os
    img_path = "static/pictures/aco.png"
    plt.savefig(img_path)
    # 校验文件是否生成
    if not os.path.exists(img_path):
        print("图片保存失败,请检查路径读写权限")
    

3. 强制清除浏览器缓存

如果之前图片加载失败导致浏览器缓存了404状态,按下Ctrl+F5强制刷新页面,加载最新资源。

4. 避免重复覆盖图片(可选优化)

若多次请求会覆盖同一张图片,建议给文件名添加时间戳,避免缓存冲突:

from datetime import datetime

timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
img_filename = f"aco_{timestamp}.png"
img_path = f"static/pictures/{img_filename}"
plt.savefig(img_path)
plot_url = url_for('static', filename=f'pictures/{img_filename}')

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 13:23:25