Flask - POST错误405方法不允许

问题描述 投票:54回答:3

我刚刚开始学习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

为什么不显示“你好”?

python http post flask
3个回答
40
投票

当方法被路由为/时,您的表单将提交给/template,除非这是一个拼写错误,您应该调整表单的action属性以指向template视图:action="{{ url_for('template') }}"


14
投票

更换:

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

有:

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

4
投票

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

更换:

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

有:

<form method="post">
© www.soinside.com 2019 - 2024. All rights reserved.