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

Flask应用显示原始HTML代码无法渲染表单,求排查解决

Flask页面显示原始HTML的排查方案

常见问题及解决方法

  • 错误使用return返回HTML字符串而非渲染模板
    必须在路由函数中使用render_template方法,而非直接返回HTML文本。正确写法:

    from flask import render_template
    
    @app.route('/')
    def index():
        # 正确:渲染templates目录下的index.html
        return render_template('index.html')
        # 错误:直接返回HTML会被浏览器当作纯文本解析
        # return '<form>...</form>'
    
  • templates目录位置或名称错误
    Flask默认读取项目根目录下的templates文件夹,确认你的目录结构为:

    /Users/davidooooo/res_recs/
        app.py
        templates/
            index.html
    

    如果目录名写错(比如写成template)或路径不符,需手动指定模板路径:

    app = Flask(__name__, template_folder='自定义模板路径')
    
  • 响应头Content-Type未正确设置
    若手动返回HTML内容,必须设置正确的响应头,否则浏览器会按纯文本处理:

    from flask import make_response
    
    @app.route('/')
    def index():
        html_content = open('templates/index.html').read()
        response = make_response(html_content)
        response.headers['Content-Type'] = 'text/html'
        return response
    

    优先推荐使用render_template,它会自动处理响应头。

  • index.html存在语法错误
    检查HTML代码是否有未闭合标签、语法错误,比如未闭合的<form>标签,这类问题会导致浏览器无法正常解析,进而显示原始代码。

快速验证步骤

  1. 简化index.html内容,比如只写<h1>测试页面</h1>,看是否能正常渲染。
  2. 确认app.py中已导入render_template,且路由函数正确调用该方法。
  3. 重启Flask应用,避免缓存影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 16:45:54