pythonの勉強中
formから送ったgetを表示するのをやってみたい。
調べてみたら簡単だった
from flask import Flask,render_template,request
app = Flask(__name__)
@app.route('/')
def test():
test_value = request.args.get('test','')
return render_template('index.html', test_value=test_value)
if __name__ == '__main__':
app.run(host='0.0.0.0', port=5000)
↓html側
<form method="get" action="">
<input type="text" name="test" value="">
<input type="submit">
</form>
{{ test_value }}
基本これだけで出来る
ここでやってるのは、まずテンプレートの読み込み
return render_template('index.html', test_value=test_value)
で、index.htmlを読み込んでるんだけど、最初に
render_template
をimportしないと使えない。
次にgetの受けだけど
test_value = request.args.get(‘test’,”)
これで出来る
request.args.get(‘test’,”)
でtestという名前変数をgetしている
2番目の引数は、もしtestがなかったときの初期値
この初期値がないとエラーになるので、とりあえず空白を入れておけばOK
この初期値に
request.args.get(‘test’,’hello’)
と入れておけば、form送信していない時は「hello」が表示される
html側では
{{ test_value }}
で表示している。
本当はifでtest_valueががある時だけ表示するようにするのがセオリーだけど
今回はあくまで表示の勉強なので、これでOK
最後に
return render_template(‘index.html’, test_value=test_value)
だけど、ここでテンプレートに変数を送らないとダメ
test_value=test_value
でtest_value変数の中身はtest_valueですよ
と伝えている。
get簡単!!
python勉強しているけど、すっごい簡単
初心者向きの言語だね

コメント