Flask - POST错误405方法不允许

dar*_*sky 56 python post http flask

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

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

我的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>
Run Code Online (Sandbox Code Playgroud)

加载表单(在收到GET时呈现它)工作正常.但是,当我单击提交按钮时,我收到POST 405错误方法不允许.为什么不显示你好?

Bur*_*lid 41

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


thi*_*nom 14

更换:

 <form action="/" method="post">
Run Code Online (Sandbox Code Playgroud)

有:

 <form action="{{ url_for('template') }}" method="post">
Run Code Online (Sandbox Code Playgroud)


小智 6

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

代替:

<form action="/" method="post">
Run Code Online (Sandbox Code Playgroud)

和:

<form method="post">
Run Code Online (Sandbox Code Playgroud)