405 方法不允许,methods=["POST", "GET"] 不工作

405 Method not Allow, methods=["POST", "GET"] not working

我在网上学习 flask 教程,也在看 POST 和 GET 上的视频。其中一个练习是 运行 一个简单的表单提交,在新的 @app.route() 上返回用户名。我尝试添加密码和用户名来模拟登录,因为我认为我很酷但失败了。代码如下。

from flask import Flask, redirect, url_for, render_template, request

app = Flask(__name__)


realUser: str = "name"
realPass: str = "pass"


@app.route("/")
def home():
    return render_template("extension.html")


@app.route("/login", methods=["POST", "GET"])
def login():
    if request.method == "POST":
        user = request.form["un"]
        password = request.form["password"]
        if realUser == user and password == realPass:
            return redirect(url_for("user", usr=user))
    else:
        return render_template("extension.html")


@app.route("/<usr>")
def user(usr):
    return f"<h1>{usr}</h1>"


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

extension.html:

{% extends "ThePurpleLounge.html" %}
{% block title %}Home Page{% endblock %}
{% block content %}
    <h1>Login</h1>
<form method="post">
    <p>Name:</p>
    <p><input type="text" name="un" /></p>

    <p>Password:</p>
    <p><input type="text" name="password" /></p>
    <p><input type="submit" value="submit" /></p>
</form>
{% endblock %}

ThePurpleLounge.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>{% block title %}{% endblock %}</title>
</head>
<body>
    {% block content %}
    {% endblock %}
</body>
</html>

我什至尝试将我的代码简化为:

from flask import Flask, redirect, url_for, render_template, request

app = Flask(__name__)


@app.route("/")
def home():
    return render_template("extension.html")


@app.route("/login", methods=["POST", "GET"])
def login():
    if request.method == "POST":
        user = request.form["un"]
        return redirect(url_for("user", usr=user))
    else:
        return render_template("extension.html")


@app.route("/<usr>")
def user(usr):
    return f"<h1>{usr}</h1>"


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

但是,它仍然显示 405 Method Not Allowed。本教程直接进入代码,所以我可能必须安装或配置一些东西。

@app.route("/") 中您不允许使用 POST 方法。因此,当您尝试发送带有 url http://127.0.0.1:5000/ 的表单时,服务器会拒绝它。 但是,如果您纠正存在另一个问题:您在另一个 url (@app.route("/login", methods=["POST", "GET"])).

处实现了登录方法

这是您的代码的有效修改(/ 重定向到 /login

from flask import Flask, redirect, url_for, render_template, request

app = Flask(__name__)


realUser: str = "name"
realPass: str = "pass"


@app.route("/")
def home():
    return redirect(url_for("login"))


@app.route("/login", methods=["POST", "GET"])
def login():
    if request.method == "POST":
        user = request.form["un"]
        password = request.form["password"]
        if realUser == user and password == realPass:
            return redirect(url_for("user", usr=user))
    else:
        return render_template("extension.html")


@app.route("/<usr>")
def user(usr):
    return f"<h1>{usr}</h1>"


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

这种代码对于理解 flask 的工作原理很有趣。要进一步了解身份验证方法,您应该看看 。