29
25

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 3 years have passed since last update.

Python Flask, GET, POST 基本動作メモ

Last updated at Posted at 2018-10-28

はじめに

この記事は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 -
image.png

GETメソッド

127.0.0.1 - - [28/Oct/2018 09:06:18] "GET /test?query=test_get HTTP/1.1" 200 -
image.png

image.png

POSTメソッド

127.0.0.1 - - [28/Oct/2018 09:07:22] "POST /test HTTP/1.1" 200 -
image.png

image.png

直接アクセス → GET

127.0.0.1 - - [28/Oct/2018 09:08:13] "GET /test HTTP/1.1" 200 -
image.png

参考

Quickstart — Flask 1.0.2 documentation
http://flask.pocoo.org/docs/1.0/quickstart/

29
25
0

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
29
25

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?