備忘録的な要素があるのでそこんとこすみません。
超絶基本
以下にテンプレ的なプログラムを書きます。
ディレクトリ構成は
Qiita/
├templates
│ ├index.html
│ └posted.html
└app.py
app.py
from flask import Flask, render_template, request
app = Flask(__name__)
## この上まではテンプレみたいなものなので
@app.route('/home')
def home():
return render_template('index.html')
@app.route('/post',methods=['POST','GET'])
def post():
if request.method == 'POST':
all = request.form
return render_template('check.html',name=name,val = val)
if __name__ == "__main__":
#ここで開くportとかも設定できる。
app.run(host='0.0.0.0',port=5000,debug=True)
ではこのプログラムの解説をしたいと思います。
解説
@app.route('/home')
これはhttp://0.0.0.0:5000/homeにアクセスしたのかを調べている?ものである。
このあとにある
return render_template('index.html')
で、templates/index.htmlを実行する。
@app.route('/post',methods=['POST','GET'])
def post():
if request.method == 'POST':
all = request.form
return render_template('posted.html',data=all)
ではPOSTかGETのmethodであれば処理をする。
またrequest.formではPOSTされたデータをdict型で受け取ります。例えばname="tsukkey"だったらrequest.form['name']と入力すればtsukkeyが参照されます。
render_template()の中のdata=allでは、POSTされた値をposted.htmlに送ってる感じです。
htmlファイルに関しては面倒なので上げませんが適当に{%%}でくくってif文とか書いとけば基本なんとかなります。