要做一個網站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的。
共勉~