WoJ
WoJ

Reputation: 30074

Posting to Flask app gives 404 even though route is defined

I ran the following Flask app and tried to post to /, but I got a 404 response. The / route is defined, why doesn't it get handled?

from flask import Flask, request

app = Flask(__name__)
app.run()

@app.route('/', methods=['POST'])
def handle_post_request():
    return str(request.form)
C:\Python35\python.exe D:/Dropbox/dev/contact.py
 * Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [03/Apr/2017 20:46:01] "POST / HTTP/1.1" 404 -

Upvotes: 2

Views: 2940

Answers (1)

davidism
davidism

Reputation: 127410

Calling app.run blocks, no code is executed after it until the server is stopped. Make sure your app is completely set up before calling run. In this case, move the route definition above the call to run.


Flask 0.11 introduced a more robust way to start applications to avoid this and other common mistakes. Completely remove app.run(). Set the FLASK_APP environment variable to your app's entry point, and call flask run.

FLASK_APP=contact.py flask run

You can also set FLASK_DEBUG=1 to enable debug mode.

In Windows, use set FLASK_APP=contact.py to set environment variables instead.

Upvotes: 3

Related Questions