Flask –フォームデータをテンプレートに送信する
httpメソッドをURLルールで指定できることはすでに見てきました。ザ・Form トリガーされた関数によって受信されたデータは、辞書オブジェクトの形式で収集し、テンプレートに転送して、対応するWebページにレンダリングできます。
次の例では、 ‘/’URLは、フォームを持つWebページ(student.html)をレンダリングします。そこに記入されたデータはに投稿されます‘/result’ をトリガーするURL result() 関数。
ザ・ results() 関数は、に存在するフォームデータを収集します request.form 辞書オブジェクトに入れて、レンダリング用に送信します result.html。
テンプレートは、次のHTMLテーブルを動的にレンダリングします。 form データ。
以下に示すのは、アプリケーションの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) 
    以下に示すのは、のHTMLスクリプトです。 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.items() %}
            <tr>
               <th> {{ key }} </th>
               <td> {{ value }} </td>
            </tr>
         {% endfor %}
      </table>
   </body>
</html> 
    Pythonスクリプトを実行し、URLを入力します http://localhost:5000/ ブラウザで。
                いつ Submit ボタンをクリックすると、フォームデータがレンダリングされます result.html HTMLテーブルの形式で。