FormからGetリクエストのパラメータを受け取る

投稿者: | 9月 5, 2022

ファイル構成

ファイル名内容
app2.pyデコレータを設定
GETリクエストのパラメータを取得する
request.args.key(‘value’) or (‘value’, ‘default vlaue’)
input.htmlformを作成し入力されたパラメータをoutputメソッドに渡す
output.html取得したパラメータを表示する

app2.py

from flask import Flask, render_template, request


# Instance Up
app = Flask(__name__)


@app.route('/')
def index():
    return render_template('input.html', title='Input section')


@app.route('/output')
def output():
    brand = request.args.get('brand')
    model = request.args.get('model')
    return render_template('output.html', brand=brand, model=model)


if __name__ == ('__main__'):
    app.run(debug=True)

input.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Input</title>
    <link rel="stylesheet" href="static/css/style.css">
</head>

<body>
    <h1>Input</h1>
    <form method="get" action="/output">
        <p><strong>Brand : </strong><input type="text" name="brand" size="30"> </p>
        <p><strong>Model : </strong><input type="text" name="model" size="30"> </p>
        <button type="submit"> Submit </button>
    </form>
</body>

</html>

output.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Output</title>
    <link rel="stylesheet" href="static/css/style.css">
</head>

<body>
    <h1>Output</h1>
    <p>Please check the following information</p>
    <p><strong>Brand : </strong>{{ brand }}</p>
    <p><strong>Model : </strong>{{ model }}</p>

    <p><a href="/">Back</a></p>
</body>

</html>

表示されたURL ” http://127.0.0.1:5000/output?brand=Gibson&model=Les+Paul “