はじめに
この記事はFlask初心者の私が Flask Quickstart を元に作成した,GETメソッド,POSTメソッドの基本的な動作についてまとめたメモです.
環境
- python 3.7.0
- flask 1.0.2
コード
test_request.py
from flask import Flask, request, Markup, abort
app = Flask(__name__)
@app.route('/')
def index():
html = '''
<form action="/test">
<p><label>test: </label>
<input type="text" name="query" value="default">
<button type="submit" formmethod="get">GET</button>
<button type="submit" formmethod="post">POST</button></p>
</form>
'''
return Markup(html)
@app.route('/test', methods=['GET', 'POST'])
def test():
try:
if request.method == 'GET':
return request.args.get('query', '')
elif request.method == 'POST':
return request.form['query']
else:
return abort(400)
except Exception as e:
return str(e)
if __name__ == '__main__':
app.run()
実行
terminal
python test_request.py
実行結果
ルート
127.0.0.1 - - [28/Oct/2018 09:05:05] "GET / HTTP/1.1" 200 -
GETメソッド
127.0.0.1 - - [28/Oct/2018 09:06:18] "GET /test?query=test_get HTTP/1.1" 200 -
↓
POSTメソッド
127.0.0.1 - - [28/Oct/2018 09:07:22] "POST /test HTTP/1.1" 200 -
↓
直接アクセス → GET
127.0.0.1 - - [28/Oct/2018 09:08:13] "GET /test HTTP/1.1" 200 -
参考
Quickstart — Flask 1.0.2 documentation
http://flask.pocoo.org/docs/1.0/quickstart/