【问题标题】:Flask HTTP Method Not Allowed MessageFlask HTTP 方法不允许消息
【发布时间】:2022-01-09 02:04:12
【问题描述】:
from flask import Flask, render_template,request

app = Flask(__name__)

@app.route('/',methods=['post'])
def main():
    if (request.method=="POST"):
        text=request.form('write')
        if(text==None):
            text=""
    else:
        text=""
    return render_template('form.html',text=text)
if __name__ == "__main__":
    app.run(debug=True)

我只想接收 POST 方法。所以我将method 选项设置为methods=["post"]。但它总是发送HTTP 405 Not Allowed Method 错误。

<html>
  <head>
    <title>Using Tag</title>
  </head>
  <body>
    <form method="POST">
    <input type="text" name="write">
    <input type="submit">
    </form>
    {{ text }}
  </body>
</html>

我想知道为什么这个应用程序只发送 HTTP 405 响应。

【问题讨论】:

  • 你的方法应该包括GETPOST

标签: python flask http-status-code-405


【解决方案1】:

要从 / 路径访问 HTML 表单,您需要在该路径中同时启用 GETPOST 请求。否则,当您尝试从浏览器访问根路径/ 时,您将获得HTTP Method not allowed error

app.py:

from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/', methods=['POST', 'GET'])
def main():
    text = ""
    if request.method == "POST":
        text = request.form['username']
    return render_template('form.html', text=text)


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

templates/form.html:

<html>
<head>
    <title>Using Tag</title>
</head>
<body>
<form method="POST">
    <input type="text" name="write">
    <input type="submit">
</form>
{{ text }}
</body>
</html>

输出:

说明(更新):

  • 要访问表单值,请使用request.form['INPUT_FIELD_NAME']
  • 我们正在向/ 路由发出GETPOST 请求。因此,我们在/ 路由的methods 选项中设置了GETPOST 请求。当我们使用浏览器查看页面时,我们向该页面发出GET 请求。当我们提交表单时,我们向该页面发出POST 请求。在这种情况下,我们将表单值存储在text 变量中,并将该值传递给模板。对于 GET 请求,我们将显示空的 text 值。

上面的sn-p和下面的sn-p是一样的:

from flask import Flask, render_template, request

app = Flask(__name__)


@app.route('/', methods=['POST', 'GET'])
def main():
    if request.method == "POST":
        text = request.form['username']
        return render_template('form.html', text=text)
    elif request.method == "GET":
        return render_template('form.html', text="")


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

参考资料:

【讨论】:

  • 非常感谢!你知道为什么我应该在选项中包含“get”方法,即使我只使用 POST 方法?
  • @Kernel_Handler,不客气!我已经更新了解释。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-03-27
  • 1970-01-01
  • 2012-09-30
  • 1970-01-01
  • 2014-01-08
  • 1970-01-01
  • 2018-12-20
相关资源
最近更新 更多