为了账号安全,请及时绑定邮箱和手机立即绑定

Python Flask:HTML 未呈现

Python Flask:HTML 未呈现

四季花海 2023-05-23 16:41:29
我有一个 html 模板,我通过使用 Flask 和 render_template() 赋予了动态特性。app = Flask(__name__, 8080)api = Api(app)class New_Info(Resource):  def get(self):    random = exc.runner()    return render_template('test3.html',book_title=random['title'],book_author=random['author'],book_text=random['text'])api.add_resource(New_Info, '/pretty')一切正常,但是当我查看网页时,我得到了这个:<!DOCTYPE html>\n<html>\n    <h1>\n        <title>{{book_title}}</title>\n    </h1>\n    <h2>\n        <title>{{book_author}}\n    </h2>\n    <body>\n        <li>{{book_text}}</li>\n    </body>\n</html>而不是正确格式化,像这样:新西兰历史上的黑暗篇章詹姆斯&middot;霍桑10 日黎明时分,比格斯少校和家人被后门敲门声从床上惊醒。打开它后,身后跟着一名仆人小伙子的比格斯少校立即中弹,并在告诉小伙子拿来步枪时倒下。男孩跑到前门,但遇到了一些豪豪斯人。他向后门走去,被受伤的少校压倒,但又站起来跑到亚麻丛中。我该如何修复它以便 html 在浏览器中正确呈现?用于返回 html 的 Python 代码from flask import Flask, render_templatefrom flask_restful import Api, Resourceapp = Flask(__name__,8080)api = Api(app)class New_Info(Resource):  def get(self):    random = exc.runner()    return render_template('test3.html',book_title=random['title'],book_author=random['author'],book_text=random['text'])api.add_resource(New_Info, '/pretty')HTML文件<!DOCTYPE html><html>    <head>        <title>Random Excerpt</title>    </head>    <body>        <h1>            {{book_title}}        </h1>        <h2>            {{book_author}}        </h2>        <div>             {{book_text}}        </div>    </body></html>
查看完整描述

2 回答

?
撒科打诨

TA贡献1934条经验 获得超2个赞

下面的代码用于 Restful API,因此它以字符串而不是 HTML 的形式返回渲染


app = Flask(__name__, 8080)

api = Api(app)


class New_Info(Resource):

  def get(self):

    random = exc.runner()

    return render_template('test3.html',book_title=random['title'],book_author=random['author'],book_text=random['text'])


api.add_resource(New_Info, '/pretty')

此代码正确呈现 html


app = Flask(__name__, 8080)


@app.route('/pretty')

def New_Info():

  random = exc.runner()

  return render_template('test3.html',book_title=random['title'],book_author=random['author'],book_text=random['text'])



查看完整回答
反对 回复 2023-05-23
?
BIG阳

TA贡献1859条经验 获得超6个赞

可能不是唯一的问题,但这可能是由于无效的 HTML:


<!DOCTYPE html>

<html>

<h1>

<title>{{book_title}}</title>

</h1>

<h2>

<title>{{book_author}}

</h2>

<body>

<li>{{book_text}}</li>

</body>

</html>

标签<title>进入<head>并且是唯一的。其他标签(如<h1>)属于<body>. 尝试这个:


<!DOCTYPE html>

<html>

    <head>

        <title>{{book_title}}</title>

    </head>


    <body>

        <h1>

            {{book_title}}

        </h1>

        <h2>

            {{book_author}}

        </h2>


        <div> 

            {{book_text}}

        </div>

    </body>

</html>

需要查看您的视图函数以检查其余代码。也许还有你的app.yaml


查看完整回答
反对 回复 2023-05-23
  • 2 回答
  • 0 关注
  • 75 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信