完成画面
問い合わせフォームで入力されたデータ: fruit_name
app.py
<input type="text" name="fruit_name" placeholder="フルーツ名を入力">
問い合わせformのデータを取得
app.py
input_text = request.form.get("fruit_name", "")
結果を表示用変数 "mix"に代入、代入できてなければエラー表示
app.py
if input_text in fruits:
mix = input_text
else:
mix = "not found"
データ送受信 テンプレ(POSTとGET両方つかう)
app.py
@app.route("/", methods=["GET", "POST"])
# 処理
表示したいdataの変数と、結果表示用変数をreturnで準備
app.py
return render_template("index.html", fruits=fruits, mix=mix)
表示したいdataを、最初に定義
app.py
app = Flask(__name__)
fruits = ["ストロベリー", "メロン", "大福", "オレンジ", "パイナップル"]
htmlにdataを表示するとき、空配列"mix"をset
def index():
mix = ""
# 処理
code 全文
app.py
from flask import Flask,render_template,request
# Flaskオブジェクトの生成
app = Flask(__name__)
fruits = ["ストロベリー", "メロン", "大福", "オレンジ", "パイナップル"]
@app.route("/", methods=["GET", "POST"])
def index():
mix = "" # 最初に mix を空で定義(これが重要)
if request.method == "POST":
input_text = request.form.get("fruit_name", "")
if input_text in fruits:
mix = input_text
else:
mix = "not found"
return render_template("index.html", fruits=fruits, mix=mix)
run.py
from app.app import app
if __name__ == "__main__":
app.run(debug=True)
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>フルーツ検索</title>
</head>
<body>
<h2>フルーツ一覧</h2>
<ul>
{% for fruit in fruits %}
<li>{{ fruit }}</li>
{% endfor %}
</ul>
<h2>問い合わせフォーム</h2>
<form method="POST">
<input type="text" name="fruit_name" placeholder="フルーツ名を入力">
<input type="submit" value="送信">
</form>
<p>選ばれたフルーツ:{{ mix }}</p>
</body>
</html>