之前我們已經看到在Flask中我們可以給URL規則指定http方法, 對應的函式可以按字典形式接收表單資料, 然後將這些資料輸送到模板中並最終渲染為網頁.
在下面的例子中, URL `/` 渲染一個含有表單的網頁(student.html). 填入到表單的資料被post到URL `/result` 然後觸發了result()
函式.
request()
函式將表單資料組裝起來, 放入request.form
字典物件中, 然後傳送到模板中渲染result.html. 這個模板將表單資料動態的渲染為一個表格.
下面是這個應用的Python程式碼:
from flask import Flask, render_template, request
app = Flask(__name__)
@app.route(`/`)
def student():
return render_template(`student.html`)
@app.route(`/result`,methods = [`POST`, `GET`])
def result():
if request.method == `POST`:
result = request.form
return render_template("result.html",result = result)
if __name__ == `__main__`:
app.run(debug = True)
下面是student.html的程式碼:
<html>
<body>
<form action = "http://localhost:5000/result" method = "POST">
<p>Name <input type = "text" name = "Name" /></p>
<p>Physics <input type = "text" name = "Physics" /></p>
<p>Chemistry <input type = "text" name = "chemistry" /></p>
<p>Maths <input type ="text" name = "Mathematics" /></p>
<p><input type = "submit" value = "submit" /></p>
</form>
</body>
</html>
下面是模板result.html的程式碼:
<!doctype html>
<html>
<body>
<table border = 1>
{% for key, value in result.iteritems() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>
{% endfor %}
</table>
</body>
</html>