Flask形式的帖子调用 - request.form是一个空的dict

时间:2017-02-14 20:31:49

标签: flask

表格login.html

<form method="POST">
    <input type="text" placeholder="username" required>
    <input type="password" placeholder="password" required>
    <button type="submit">Sign in</button>
</form>

app.py

@app.route("/", methods=["GET", "POST"])
def login():
    if request.method == "POST":
        print(request.form)    # prints empty dict
    return render_template("login.html")

2 个答案:

答案 0 :(得分:1)

表单中输入的name参数在任何html表单中都需要POST,否则它们将保持未处理状态。

所以正确的HTML会是login.html

<form method="POST">
    <input type="text" placeholder="username" name="username" required>
    <input type="password" placeholder="password" name="password" required>
    <button type="submit">Sign in</button>
</form>

现在,烧瓶应该能够按名称和值dict向上输入元素。

答案 1 :(得分:0)

它返回空字典,因为您没有指定所请求对象的名称。您应该从html中指定名称:

<input type="text" placeholder="username" name="username" required>

,在Python中使用类似:

request.form['username'] 要么 request.form.get('username')

代替:(request.form)

还有一个话题可以看看: How to get data received in Flask request