flask_restful template: 浏览器将flask模板解释为Html代码

要做一个网站demo, 准备用flask来做。按照官网的例子,照猫画虎,做了一个project。但是我写的html代码并没有像官网那样被浏览器按照html语言解释,而是被当做字符串解释了。如下图:
在这里插入图片描述
更别说我调查半天挑出来的css样式框架都没应用。
网上资料也是比较少。自己也很纳闷,为什么代码并没有问题,却跟官网显示的截然不同?
查找一番,这个回答给了我启发:
get rid of the api. use app function only. your using flask not a restful api.
参考:https://stackoverflow.com/questions/46232730/render-template-in-flask-returns-html-code-in-browser

其实我也一直纠结着flask和flask_restful他们之间到底有什么区别,抱着这样的疑惑没有解决,我就栽了跟头。
于是我将主程序的代码从下面这样(错误示范,请勿模仿):

class TodoSimple(Resource):
    def get(self):
        # headers = {'Content-Type': 'text/html'}
        return render_template('test.html')

    def put(self, todo_id):
        todos[todo_id] = request.form['data']
        return {todo_id: todos[todo_id]}


api.add_resource(TodoSimple, '/test')


@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'app.ico', mimetype='image/vnd.microsoft.icon')

改成了下面这样:

@app.route('/favicon.ico')
def favicon():
    return send_from_directory(os.path.join(app.root_path, 'static'),
                               'app.ico', mimetype='image/vnd.microsoft.icon')


@app.route('/test')
def test():
    return render_template('test.html')

刷新浏览器,显示正常啦:
在这里插入图片描述
flask是用来快速搭建web程序的,而flask_restful是flask和restful api的结合体,主要是用来做api的。

共勉~

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章