[譯]Flask教程--將表單數據發送到模板

以前咱們已經看到在Flask中咱們能夠給URL規則指定http方法, 對應的函數能夠按字典形式接收表單數據, 而後將這些數據輸送到模板中並最終渲染爲網頁.html

在下面的例子中, URL '/' 渲染一個含有表單的網頁(student.html). 填入到表單的數據被post到URL '/result' 而後觸發了result()函數.python

request()函數將表單數據組裝起來, 放入request.form字典對象中, 而後發送到模板中渲染result.html. 這個模板將表單數據動態的渲染爲一個表格.flask

下面是這個應用的Python代碼:app

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的代碼:post

<!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>
相關文章
相關標籤/搜索