【问题标题】:Rendering HTML webpage with restful flask - Webpage not displaying properly使用 RESTful Flask 渲染 HTML 网页 - 网页无法正确显示
【发布时间】:2020-02-17 03:41:23
【问题描述】:

我正在尝试使用 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')

【问题讨论】:

  • 这可能是因为你继承自Resource。 RESTful API 通常返回 JSON 字符串而不是呈现 HTML 内容。
  • 你能说出响应的内容类型吗?可能是烧瓶-Restful 将默认值从 text/html 更改为 text 或 json。
  • 我应该如何解决这个问题?
  • 类型是unicode

标签: python html flask-restful


【解决方案1】:

您可能需要从flask 导入make_repsone 以使用标题信息呈现您的html。

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

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2020-11-27
    • 1970-01-01
    • 1970-01-01
    • 2014-12-20
    • 2019-12-19
    相关资源
    最近更新 更多