W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
我們已經(jīng)看到,可以在 URL 規(guī)則中指定 http 方法。觸發(fā)函數(shù)接收的 Form 數(shù)據(jù)可以以字典對象的形式收集它并將其轉(zhuǎn)發(fā)到模板以在相應(yīng)的網(wǎng)頁上呈現(xiàn)它。
在以下示例中,'/' URL 會呈現(xiàn)具有表單的網(wǎng)頁(student.html)。
填入的數(shù)據(jù)會發(fā)布到觸發(fā) result() 函數(shù)的 '/result' URL。
result() 函數(shù)收集字典對象中的 request.form 中存在的表單數(shù)據(jù),并將其發(fā)送給 result.html。
該模板動態(tài)呈現(xiàn)表單數(shù)據(jù)的 HTML 表格。
下面給出的是應(yīng)用程序的 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 腳本。
<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>
下面給出了模板( result.html )的代碼:
<!doctype html>
<table border = 1>
{% for key, value in result.items() %}
<tr>
<th> {{ key }} </th>
<td> {{ value }}</td>
</tr>
{% endfor %}
</table>
運行 Python 腳本,并在瀏覽器中輸入 URL http://localhost:5000/。
當(dāng)點擊提交按鈕時,表單數(shù)據(jù)以 HTML 表格的形式呈現(xiàn)在 result.html 上。
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: