
flask 应用显示 html 源码而非渲染页面,通常因文件路径错误、mime 类型误设或模板未被正确加载导致;本文详解目录结构、render_template 使用规范及调试要点。
flask 应用显示 html 源码而非渲染页面,通常因文件路径错误、mime 类型误设或模板未被正确加载导致;本文详解目录结构、render_template 使用规范及调试要点。
在 Flask 中,若浏览器直接显示 HTML 文件的原始文本(如
...),而非渲染为可视化网页,说明服务器未以 text/html MIME 类型响应,或根本未成功执行模板渲染逻辑。结合您提供的项目结构和代码,问题根源并非 HTML 内容本身,而在于 Flask 的运行机制与开发环境配置。✅ 正确前提:目录结构与模板位置
Flask 的 render_template() 严格要求 HTML 文件必须位于 templates/ 子目录下(默认路径)。您已正确组织为:
project_folder/
├── app.py
├── templates/ ← 必须存在且命名准确
│ └── index.html ← 文件名需与 render_template('index.html') 一致
└── models/
└── BreastCancerDetection.h5
✅ 此结构无误 —— 无需修改。
⚠️ 关键问题分析与修复
1. 不要用纯文本编辑器保存 HTML(如 macOS TextEdit)
TextEdit 默认以 RTF 或纯文本格式保存 .html 文件,可能在文件开头插入不可见的 BOM 字符或格式控制符,导致 Flask 读取时解析异常,甚至触发 500 Internal Server Error 而降级返回原始 HTML 文本(表现为“显示源码”)。
✅ 解决方案:使用专业代码编辑器(如 VS Code、Atom、Sublime Text),并确保文件编码为 UTF-8 无 BOM,文件类型明确为 HTML。
2. 路由逻辑中缺失关键图像处理健壮性检查
原 predict 视图函数存在两个高危隐患:
- 未校验上传文件是否存在(request.files.get() 更安全);
- 未处理 uploaded_file.filename == '' 的空上传场景;
- 直接将 request.files['...'] 传入 image.load_img() 会失败(该函数接收文件路径字符串,而非文件对象)。
✅ 修正后的 predict 函数如下:
@app.route('/predict', methods=['POST'])
def predict():
# 安全获取上传文件
uploaded_file = request.files.get('BreastUltrasoundImage')
if not uploaded_file or uploaded_file.filename == '':
return render_template('index.html', predictions="No file selected.")
# 保存临时文件或直接读取字节流(推荐)
try:
# 方案A:保存后加载(适合大图或需复用)
# temp_path = os.path.join('/tmp', uploaded_file.filename)
# uploaded_file.save(temp_path)
# img = image.load_img(temp_path, target_size=(256, 256))
# 方案B:内存中直接加载(更高效,推荐)
import io
img_bytes = io.BytesIO(uploaded_file.read())
img = image.load_img(img_bytes, target_size=(256, 256))
img_array = image.img_to_array(img) / 255.0
img_array = np.expand_dims(img_array, axis=0)
predictions = model.predict(img_array)
class_label = int(np.argmax(predictions, axis=1)[0])
result_text = "Malignant" if class_label == 1 else "Benign"
return render_template('index.html', predictions=result_text)
except Exception as e:
return render_template('index.html', predictions=f"Error: {str(e)}")
3. HTML 表单需补充 CSRF 防护(生产环境必需)
当前表单缺少 CSRF token,虽不影响本地调试,但暴露安全风险。建议后续集成 Flask-WTF:
<!-- 在 form 内添加 -->
{{ form.hidden_tag() }}
? 快速自检清单
| 检查项 | 正确做法 |
|---|---|
| ✅ 文件编码 | HTML 文件保存为 UTF-8(无 BOM),编辑器状态栏确认 |
| ✅ 模板路径 | templates/index.html,非 index.html 同级或 static/ 下 |
| ✅ 视图返回值 | return render_template(...),绝非 return open(...).read() 或字符串拼接 HTML |
| ✅ MIME 类型验证 | 浏览器开发者工具 → Network → 查看响应头 Content-Type: text/html |
? 总结
“显示 HTML 源码”本质是 Flask 未能成功执行模板渲染,常见于:
? 编辑器保存格式污染(首要排查!);
? render_template() 调用失败后 Flask 返回了原始文件内容(如 send_file 误用);
? 路由未捕获异常,导致 500 错误页被浏览器当作文本显示。
请优先用 VS Code 重写 index.html,替换 predict 函数为上述健壮版本,并启用 app.run(debug=True) 查看终端报错——90% 的同类问题可立即定位解决。
前端入门到VUE实战笔记:立即使用
在学习笔记中,你将探索 前端 的入门与实战技巧!











