python - 使用 Restful Flask 渲染 HTML 网页 - 网页无法正确显示

标签 python html flask-restful

我正在尝试使用 Restful Flask api 在本地主机上渲染 HTML 页面。 HTML 页面的内容显示为带有“”的字符串,而不是页面。

class data(Resource):
    def get(self):
        #return "Welcome!"
        return render_template('index.html')


api.add_resource(data,'/')

我的index.html文件包含以下内容

<!DOCTYPE html>
<html>
<body>
<h1>Welcome to the site!</h1>
</body>
</html>

运行代码后,在网页( http://localhost:5000/ )上得到以下内容

"<!DOCTYPE html>\n<html>\n<body>\n<h1>Welcome to the Data Hosting Service</h1>\n</body>\n</html>"

另一方面,它返回文本“欢迎!”通常情况下。你能帮我吗?

更新: 在用户的帮助下,我通过更改响应类型解决了这个问题,如下所示,

from flask import Response, render_template
return Response(render_template('index.html'),mimetype='text/html')

最佳答案

您可能需要从 flask 导入 make_repsone 来渲染带有 header 信息的 html。

from flask import make_response, render_template
headers = {'Content-Type': 'text/html'}
return make_response(render_template('index.html'),200,headers)

希望这会有所帮助。

关于python - 使用 Restful Flask 渲染 HTML 网页 - 网页无法正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38945635/

相关文章:

python - 旋转矩形直到碰到三角形,并确定交点

python - Pandas ,数据帧 : Splitting one column into multiple columns

javascript - 类型错误 : Cannot read property 'classList' of undefined

python - 无法使用 Flask Blueprints 和 Swagger UI 获取 API 规范

python - 在 Pandas 中选择两个 DataFrame 之间的唯一行

python - Buildbot 安装设置错误

html - Firefox 和 Chrome 之间神秘的 2px 差异

jquery - 只有在用户单击超链接(条款和条件?)后才能选中复选框吗?

python - 无法导入模块python ImportError

python flask-restful 无法在资源类中获取应用程序访问权限