一、URL構建
url_for()函數對于動態構建特定函數的URL非常有用。 該函數接受函數的名稱作為第一個參數,并接受一個或多個關鍵字參數,每個參數對應于URL的變量部分。
from flask import Flask, redirect, url_forapp = Flask(__name__)@app.route('/admin')def hello_admin():return 'Hello Admin'@app.route('/guest/<guest>')def hello_guest(guest):return 'Hello %s as Guest' % guest@app.route('/user/<name>')def user(name):if name =='admin':return redirect(url_for('hello_admin'))else:return redirect(url_for('hello_guest',guest = name))if __name__ == '__main__':app.run(debug = True)
如上面代碼中,url_for接收了hello_admin和hello_guest函數作為第1個參數,根據傳入不同的值,執行不同的函數。
二、模板
Flask可以以HTML形式返回綁定到某個URL的函數的輸出。如果從Python代碼生成HTML內容非常麻煩,尤其是在需要放置可變數據和Python語言元素(如條件或循環)時。經常需要轉義HTML代碼。這種方式不推薦。
另一種方式是利用Jinja2模板引擎技術,而不需要從函數返回硬編碼HTML。如下代碼所示,可以通過render_template()函數渲染HTML文件。
1、編寫hello.py文件
from flask import Flaskapp = Flask(__name__)@app.route('/')def index():return render_template(‘hello.html’)if __name__ == '__main__':app.run(debug = True)
然后在該腳本所在的同一文件夾中創建templates目錄,并在里邊創建html文件hello.html,寫入如下代碼;
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Flask 模板使用</title></head><body><h1>Hello {{ name }}!</h1></body></html>
執行上面的hello.py文件,在瀏覽器中訪問,可以看到參數中的kelly替換為html中的 {{ name }}
拓展:
1、條件結構
Jinja2模板引擎使用以下分隔符來從HTML轉義。
{% ... %} 用于多行語句
{{ ... }} 用于將表達式打印輸出到模板
{# ... #} 用于未包含在模板輸出中的注釋
# ... ## 用于單行語句
在以下示例中,演示了在模板中使用條件語句。 hello()函數的URL規則接受整數參數。 它傳遞給hello.html模板。 在它里面,收到的數字(標記)的值被比較(大于等于或小于60),因此在HTML執行了有條件渲染輸出。
python腳本:
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/hello/<int:score>')
def hello_score(score):return render_template('score.html',marks=score)if __name__ == '__main__':app.run(port=5000,debug=True)
html代碼:
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Flask模板示例</title></head><body>{% if marks>=60 %}<h1> 通過考試!</h1>{% else %}<h1>未通過考試!</h1>{% endif %}</body></html>
啟動python程序,在瀏覽器中輸入不同的分數:
2、循環結構
循環結構也可以在模板內部使用,在以下腳本中,當在瀏覽器中打開
URL => http:// localhost:5000/result時,result()函數將字典對象發送到模板文件:?results.html?。
result.html?的模板部分采用for循環將字典對象result{}的鍵和值對呈現為HTML表格的單元格。
python腳本:
from flask import Flask,render_template
app = Flask(__name__)
@app.route('/score')
def score():dict1 = {'python': 90, 'java': 80, 'go': 70}return render_template('score_table.html',score = dict1)if __name__ == '__main__':app.run(port=5300,debug=True)
html代碼:
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>Flask模板示例</title></head><body><table border = 1>{% for key, value in score.items() %}<tr><th> {{ key }} </th><td> {{ value }} </td></tr>{% endfor %}</table></body></html>
執行后輸出: