Flask中的方法不被允许的错误

5 投票
1 回答
15206 浏览
提问于 2025-04-18 08:53

我在尝试提交请求时遇到了这个错误。

Method Not Allowed

The method is not allowed for the requested URL.

这是我的flask代码……

@app.route("/")
def hello():
  return render_template("index.html")

@app.route("/", methods=['POST','GET'])
def get_form():
  query = request.form["search"]
  print query

还有我的index.html文件。

<body>

<div id="wrap">
  <form action="/" autocomplete="on" method="POST">
    <input id="search" name="search" type="text" placeholder="How are you feeling?">
     <input id="search_submit" value="Send" type="submit">
  </form>
</div>

  <script src="js/index.js"></script>

</body>

补充一下……这是我完整的flask代码:

from flask import  Flask,request,session,redirect,render_template,url_for
import flask
print flask.__version__
app = Flask(__name__)

@app.route("/")
def entry():
    return render_template("index.html")

@app.route("/data", methods=['POST'])
def entry_post():
    query = request.form["search"]
    print query
    return render_template("index.html")


if __name__ == "__main__":
    app.run()

1 个回答

5

你正在向 entry() 函数发送数据,但你的 entry_post() 函数监听的是一个不同的路径;它只会接收 /data 的请求,而不是 /

@app.route("/data", methods=['POST'])
def entry_post():

默认情况下,/ 路径不接受 POST 请求,它只允许 GETHEADOPTIONS 请求。

所以你需要相应地调整你的表单:

<form action="/data" autocomplete="on" method="POST">

要注意的是,Flask 不会自动重新加载你的代码,除非你开启调试模式

app.run(debug=True)

撰写回答