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 回應。
uj5u.com熱心網友回復:
要從/路徑訪問 HTML 表單,您需要在該路徑中同時啟用GET和POST請求。否則,當您嘗試/從瀏覽器訪問根路徑時,您將獲得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'].
參考:
- 請求物件的 Flask 檔案
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/405638.html
標籤:
上一篇:存盤在變數中的命令在if陳述句中不被識別為coomand-LinuxBash腳本
下一篇:FastAPI不加載靜態檔案
