0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Flaskに関するメモ

0
Last updated at Posted at 2019-12-11

備忘録的な要素があるのでそこんとこすみません。

超絶基本

以下にテンプレ的なプログラムを書きます。
ディレクトリ構成は

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)

ではPOSTGETのmethodであれば処理をする。
またrequest.formではPOSTされたデータをdict型で受け取ります。例えばname="tsukkey"だったらrequest.form['name']と入力すればtsukkeyが参照されます。
render_template()の中のdata=allでは、POSTされた値をposted.htmlに送ってる感じです。
htmlファイルに関しては面倒なので上げませんが適当に{%%}でくくってif文とか書いとけば基本なんとかなります。

0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?