English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Flask フォーム処理

URLルールでhttpメソッドを指定することができます。URLマッピングの関数は受け取ったフォームデータを辞書オブジェクトの形式で収集し、それをテンプレートに転送して、対応するウェブページ上に表示します。

以下の例では、URL => / フォームを持つウェブページを表示します( student.html)。入力されたデータはresult()関数をトリガーするURL => /result 中。

results()関数はrequest.formに存在するフォームデータを収集し、それをresultに送信します。 result.html 表示します。

このテンプレートはフォームデータを動的にHTMLテーブルに表示します。

以下にPythonのアプリケーションコードを示します -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.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 w3codebox
# Author by : ja.oldtoolbag.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>物理点数: <input type="text" name="Physics" /></p>
          <p>化学点数: <input type="text" name="Chemistry" /></p>
          <p>数学の分数: <input type ="text" name = "Mathematics" /></p>
          <p><input type = "submit" value = "送信" /></p>
       </form>
    </body>
 </html>

テンプレートコード(result.html)は以下に示します -

# Filename : example.py
# Copyright : 2020 By w3codebox
# Author by : ja.oldtoolbag.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>

Pythonスクリプトを実行し、ブラウザでURLを入力してください => http://localhost:5000/ 。以下に結果を示します -

クリックすると 送信ボタンをクリックすると、フォームデータがHTMLテーブルの形式で表示されます result.html 以下に示すように、中国語で -