Flask 將表單數(shù)據(jù)發(fā)送到模板

2022-08-16 10:38 更新

我們已經(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/。

Submit Marks

當(dāng)點擊提交按鈕時,表單數(shù)據(jù)以 HTML 表格的形式呈現(xiàn)在 result.html 上。

Marks Table


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號