Home > database >  Flask HTTP Method Not Allowed Message
Flask HTTP Method Not Allowed Message

Time:01-08

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.

CodePudding user response:

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:

output

Explanation:

  • To access the form value use request.form['INPUT_FIELD_NAME'].

References:

  •  Tags:  
  • Related