データ送信全体的なプロセスの一つ一つがイメージできないでいます。
(特にpostってやつがむずいです。データを送信する機能らしいんですが。)
ということで一度整理してみたのでまちがってる部分を教えてください。
あと、ここでpostがどう機能しているのかも教えていただけると嬉しいです。
1番をクリック
-> 関数resultにfruit_noが渡される。関数実行。
->result2.htmlの表示
->佐藤と入力
->フォームを送信し、outputがデータを受け取る。関数の実行.
->output2.htmlの表示
構成は以下の通りです。
templates
index2.html
result2.html
output2.html
main3.py
html
1<!-- index2.html --> 2<!DOCTYPE html> 3<html> 4<head> 5<meta charset="UTF-8"> 6<title>選択 - くじ引き</title> 7</head> 8<body> 9 <h1>くじ引き</h1> 10 <p>番号を選んで果物を受け取りましょう。</p> 11 <ul> <!-- あれ、今回はクエリストリングじゃないね。 --> 12 <li><a href="/result/1/">1番</a></li> 13 <li><a href="/result/2/">2番</a></li> 14 <li><a href="/result/3/">3番</a></li> 15 </ul> 16</body> 17</html> 18
html
1<!-- result2.html --> 2<!DOCTYPE html> 3<html> 4<head> 5<meta charset="UTF-8"> 6<title>結果 - くじ引き</title> 7</head> 8<body> 9 <h1>結果</h1> 10 <p><strong> {{ fruit }} </strong>が当たりました。</p> 11 12 <form method="post" action="{{ url_for('output', fruit_no=fruit_no) }}"> 13 <p>名前:<input type="text" name="name" size="40"></p> 14 <button type="submit">送信</button> 15 </form> 16 <p><a href="/">戻る</a></p> 17</body> 18</html> 19
html
1<!-- output2.html --> 2<!DOCTYPE html> 3<html> 4<head> 5<meta charset="utf-8"> 6<title>お名前の表示</title> 7</head> 8<body> 9 <p>「{{ name }}」は、 <strong>{{ fruit }}</strong>を受け取りました。</p> 10 <p><a href="/">戻る</a></p> 11</body> 12</html> 13
python
1from flask import Flask, render_template, request 2app = Flask(__name__) 3 4fruits = {'1': 'もも', '2': 'りんご', '3': 'みかん'} 5 6 7@app.route("/") 8def index(): 9 return render_template('index2.html') 10 11 12@app.route("/result/<fruit_no>/") 13 14def result(fruit_no): 15 return render_template('result2.html', 16 fruit=fruits[fruit_no], 17 fruit_no=fruit_no) 18 19 20@app.route("/output/<fruit_no>/", methods=['POST']) 21#この関数はデータを送信しようとしているはずだからpostを使ってみる。正直リクエストしてるからgetもあっていいと思うけどね。 22# ->あってもなくても結果は変わらないな。 23 24def output(fruit_no): 25 your_name = request.form['name'] 26 return render_template('output2.html', 27 name = your_name, 28 fruit = fruits[fruit_no]) 29
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/05/08 23:57