通過
return
或jsonify
返回數據。使用者用瀏覽器等用具打開時,只能查看到源數據。
使用render_template
調用html頁面,並結合html參數,
示例
- 創建python程序
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
import json
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
@app.route("/index.html")
def index():
flask_data = 'Hello Flask!'
return render_template('index.html', flask_data=flask_data)
if __name__ == '__main__':
app.run('0.0.0.0', 5000)
- 創建html文件
flask項目根目錄下創建
templates
目錄(用來存放html文件)。render_template
從templates
目錄讀取html
文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
</head>
<body>
<h1>{{ flask_data }}</h1>
</body>
</html>
render_template
調用templates
目錄中的index.html
。並將flask_data
數據傳遞至html文件中的{{ flask_data }}
進行展示
傳遞字典
當 flask_data = {'name':'xiaoming', 'age':8}
需瀏覽器中展示 name 對應的值 xiaoming 。
變量應寫成{{ flask_data.name }}