Flask 表單處理

我們已經(jīng)看到,可以在URL規(guī)則中指定http方法。URL映射的函數(shù)接收到的表單數(shù)據(jù)可以以字典對(duì)象的形式收集,并將其轉(zhuǎn)發(fā)給模板以在相應(yīng)的網(wǎng)頁(yè)上呈現(xiàn)它。

在以下示例中,URL => / 呈現(xiàn)具有表單的網(wǎng)頁(yè)( student.html)。填充的數(shù)據(jù)會(huì)提交到觸發(fā)result()函數(shù)的URL => /result 中。

results()函數(shù)收集字典對(duì)象中request.form中存在的表單數(shù)據(jù),并將其發(fā)送給 result.html 并顯示出來(lái)。

該模板動(dòng)態(tài)呈現(xiàn)表單數(shù)據(jù)的HTML表格。

下面給出的是Python的應(yīng)用程序代碼 -

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
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腳本的代碼。

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
<html>
 <head>
 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <title>Flask示例</title>
 </head>
    <body>
       <form action = "http://localhost:5000/result" method = "POST">
          <p>姓名 <input type = "text" name = "Name" /></p>
          <p>物理分?jǐn)?shù): <input type = "text" name = "Physics" /></p>
          <p>化學(xué)分?jǐn)?shù): <input type = "text" name = "Chemistry" /></p>
          <p>數(shù)學(xué)分?jǐn)?shù): <input type ="text" name = "Mathematics" /></p>
          <p><input type = "submit" value = "提交" /></p>
       </form>
    </body>
 </html>

模板代碼(result.html)在下面給出 -

# Filename : example.py
# Copyright : 2020 By Nhooo
# Author by : www.soo66.com
# Date : 2020-08-08
<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 result.items() %}
             <tr>
                <th> {{ key }} </th>
                <td> {{ value }} </td>
             </tr>
          {% endfor %}
       </table>
    </body>
 </html>

運(yùn)行Python腳本,并在瀏覽器中輸入U(xiǎn)RL => http://localhost:5000/ 。結(jié)果如下所示 -

瀏覽器中輸入U(xiǎn)RL

當(dāng)點(diǎn)擊 提交按鈕時(shí),表單數(shù)據(jù)以HTML表格的形式呈現(xiàn)在 result.html 中,如下所示 -

HTML表格的形式呈現(xiàn)

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清