Reputation: 21
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)
I want to receive only POST method. So I set method
option to methods=["post"]
. But it always sends HTTP 405 Not Allowed Method
error.
<html>
<head>
<title>Using Tag</title>
</head>
<body>
<form method="POST">
<input type="text" name="write">
<input type="submit">
</form>
{{ text }}
</body>
</html>
I want to know reason why this application only sends HTTP 405 response.
Upvotes: 0
Views: 761
Reputation: 13651
To access the HTML form from /
path you need to enable both GET
and POST
request in that route. Otherwise when you try to access the root path /
from your browser, you will get the 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>
Output:
Explanation (Updated):
request.form['INPUT_FIELD_NAME']
.GET
and POST
requests to the /
route. So, we set GET
and POST
requests in the methods
options of the /
route. When we are viewing the page using the browser, we make GET
request to that page. When we submit the form, we make POST
request to that page. In this case, we are storing the form value in the text
variable and pass the value to the template. For GET
request we are showing the empty text
value.The above snippet is the same as the following snippet:
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)
References:
Upvotes: 2