Python 3 – Flaskテンプレート(Jinja2)にデータを送信する

Python

Flaskがフォームデータをテンプレートに送信するFlaskがフォームデータをテンプレートに送信するURLルールでhttpメソッドを指定できることを確認しました。トリガー関数によって受信されたフォームデータは、辞書オブジェクトの形式で収集され、テンプレートに転送されます。対応するWebページにレンダリングします。

関連コース: Python Flask:Flaskを使用してWebアプリを作成する

URLルーティング

次の例では、「/」URLはフォーム(student.html)を含むWebページを示します。入力されたデータは、result()関数をトリガーした「/ result」URLに公開されます。

results()関数は、辞書オブジェクトのrequest.formに存在するフォームデータを収集し、result.htmlに送信します。

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from flask import Flask, render_template, request
app = Flask(name)
@app.route("https://pythonbasics.org/")
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を作成します

1
2
3
4
5
6
7
<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>

ブラウザのURLを開くと、テンプレートは次のようになります。

データを表示

そしてresult.html

1
2
3
4
5
6
7
8
9
10
11
<!doctype html>
<table border = 1>
{% for key, value in result.items() %}

<tr>
<th> {{ key }} </th>
<td> {{ value }} </td>
</tr>

{% endfor %}
</table>

Pythonスクリプトを実行し、URLを入力します localhost:5000 / ブラウザで。

次に、[送信]をクリックすると、テンプレートにデータが出力されます。

フラスコテンプレートデータを表示(result.html)

関連コース: Python Flask:Flaskを使用してWebアプリを作成する

Hope this helps!

Source link

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です