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>标签,这类问题会导致浏览器无法正常解析,进而显示原始代码。
快速验证步骤
- 简化
index.html内容,比如只写<h1>测试页面</h1>,看是否能正常渲染。 - 确认
app.py中已导入render_template,且路由函数正确调用该方法。 - 重启Flask应用,避免缓存影响。
内容的提问来源于stack exchange,提问作者davidocodes
相关产品推荐
相关产品推荐

