我無法將我的網址重定向到另一條路線。
我想重定向到/success但它沒有到達那里。
app.route("/success") 中的列印陳述句從未被實作,也從不回傳任何內容。
我嘗試了很多錯誤處理,但無法找出問題所在。
應用程式.py
app = Flask(__name__)
REGISTRANTS = {}
SPORT=["Cricket", "Football", "Badminton", "Kho-Kho", "Kabaddi"]
@app.route("/", methods = ["GET", "POST"])
def index():
if request.method == "GET":
return render_template("index.html", sports = SPORT)
name = request.form.get("name")
sport = request.form.get("sport")
if not name:
return render_template("failure.html", message="Name not entered")
if not sport:
return render_template("failure.html", message="Sport not selected")
if sport not in SPORT:
return render_template("failure.html", message="Sport not in list. Don't try to hack our website.")
if request.method == "POST":
REGISTRANTS[name]=sport
print("yes")
return redirect("/success")
@app.route("/success", methods=["POST"])
def success():
print("Please work")
return render_template("success.html", registrants = REGISTRANTS)
索引.html
{% extends "layout.html" %}
{% block body %}
<h1 style="text-align:center;">Register</h1>
<form action="/" method="post">
<input name="name" type="text" autocomplete="off" autofocus placeholder="Name">
<select name="sport">
<option value="" disabled selected>Sport</option>
{% for sport in sports %}
<option value="{{sport}}">{{sport}}</option>
{% endfor %}
</select>
<input type = "submit" value="Register">
</form>
{% endblock %}
布局.html
<html lang="en">
<head>
<meta name ="viewport" content = "initial-scale=1", width="device-width">
<title>hello</title>
</head>
<body>
{% block body %}{% endblock %}
</body>
</html>
成功.html
{% block body %}
hello, {{name}}. Thanks for Registering for {{sport}}!
<h1>Registrants</h1>
<table style="border: 2px solid black">
<thead>
<tr style="border: 2px solid black">
<th style="border: 2px solid black">Name</th>
<th style="border: 2px solid black">Sport</th>
</tr>
</thead>
<tbody>
{% for name in registrants %}
<tr style="border: 2px solid black">
<td style="border: 2px solid black">{{name}}</td>
<td style="border: 2px solid black">{{registrants[name]}}</td>
</tr>
{% endfor %}
</tbody>
</table>
{% endblock %}
我是Flask 的新手。請指導我。
uj5u.com熱心網友回復:
重定向請求會添加一個 HTTP 標頭并與狀態代碼 302 一起發送,這會導致瀏覽器向指定位置發送新的 GET 請求。這意味著成功路由上的傳入請求被拒絕,因為它只允許 POST 方法。
我認為如果你在這里使用 get 方法它應該可以作業。
@app.route("/success")
def success():
print("Please work")
return render_template("success.html", registrants = REGISTRANTS)
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/349227.html
