6
4

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.

flaskのrequest.form[]とrequest.form.get()の違い

Last updated at Posted at 2021-10-02

はじめに

今までrequest.form.get()でコードを書いていたが、他の人のコードを見るとrequest.form[]という書き方がちらほら。
これらの違いは何か調べてみた。

結論

request.form.get()は探しているものがなければエラーが出ないようにデフォルトの値を返すそう
request.form[]はデフォルトの値がないため探しているものがなければエラーをはいてしまう

そう言われてもいまいちわからないので実際に試してみた

app.py
@app.route("/input", methods=['GET', 'POST'])
def input():
    if request.method == "POST":
        #if request.form['name']:
        if request.form.get('name'):
            return "成功!"
        else:
            return "失敗"
    else:
        return render_template("input.html")
input.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input</title>
</head>
<body>
    <form action="/input" method="POST">
        <input type="text" name="name">
        <input type="submit">
    </form>
</body>
</html>

if request.form['name']:の場合

  • input type="text" name="name"があれば成功と表示される(正常に動作する)

  • input type="text" name="name"がなければエラーになってしまう(ステータスコード400)

  • -> 例外処理が必須

if request.form.get('name'):

  • input type="text" name="name"があれば成功と表示される(正常に動作する)

  • input type="text" name="name"がなければ失敗と表示される

  • -> 例外処理をしなくても良い(?)

ちなみに

  • request.form.get()がデフォルトで返す値はNone
app.py

@app.route("/input", methods=['GET', 'POST'])
def input():
    if request.method == "POST":
        #if request.form['name']:
        if request.form.get('name'):
            return "成功!"
        else:
            test = request.form.get('name')
            return render_template("input.html", test=test)
    else:
        return render_template("input.html")
input.html
<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Input</title>
</head>
<body>
    <p>{{ test }}</p>
    <form action="/input" method="POST">
        <input type="text" name="nam"> #ここが間違っている
        <input type="submit">
    </form>
</body>
</html>

スクリーンショット 2021-10-02 16.14.49.png

おわりに

どちらにもメリット・デメリットがあるので必要に応じて使い分けたい。

参考

6
4
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
6
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?