Flask - POST错误405方法不允许

时间:2012-08-29 13:53:51

标签: python http post flask

我刚刚开始学习Flask,我正在尝试创建一个允许 POST 方法的表单。

这是我的方法:

@app.route('/template', methods=['GET', 'POST'])
def template():
    if request.method == 'POST':
        return("Hello")
    return render_template('index.html')

我的index.html

<html>

<head>
  <title> Title </title>
</head>

<body>
  Enter Python to execute:
  <form action="/" method="post">
    <input type="text" name="expression" />
    <input type="submit" value="Execute" />
  </form>
</body>

</html>

加载表单(在收到 GET 时呈现)可以正常工作。当我点击提交按钮时,我会收到POST 405 error Method Not Allowed

为什么不显示“Hello”

3 个答案:

答案 0 :(得分:39)

当方法路由到/时,您的表单正在提交至/template,除非是拼写错误,您应该调整表单的action属性以指向template查看:action="{{ url_for('template') }}"

答案 1 :(得分:14)

替换:

 <form action="/" method="post">

使用:

 <form action="{{ url_for('template') }}" method="post">

答案 2 :(得分:4)

如果省略action属性,表单将发布到当前网址。

替换:

<form action="/" method="post">

使用:

<form method="post">