Python – Gunicorn leads to Flask’s add_url_rule by causing 404

Gunicorn leads to Flask’s add_url_rule by causing 404… here is a solution to the problem.

Gunicorn leads to Flask’s add_url_rule by causing 404

I

used Gunicorn on Heroku to try and provide a basic web page and it works fine if I use a normal route decorator. For example:

from flask import Flask

app = Flask(__name__)
@app.route('/')
def a():
    return "b"
if __name__ == "__main__":
    app.run()

This code will run fine and correctly provide “b” at the index. However, if I use the add_url_route function instead of a route decorator, it will only respond with a 404.

from flask import Flask

app = Flask(__name__)
def a():
    return "b"
if __name__ == "__main__":
    app.add_url_rule('/', 'index', a)
    app.run()

Here is my program file :

web: gunicorn test:app --log-file=-

It’s worth noting that when I run it from the command line using Python (python test.py), both work fine. Am I doing something wrong here?
I’m using Python 3.6.3 and Flask 0.12.2.

Solution

app.add_url_rule line is only executed when you run the Python script directly. When you just import the script (which is what gunicorn does), no routes are configured at all and any request will result in a 404.

This also explains why both versions work when executed locally.

If you really want to, you can move the app.add_url_rule outside the main block. However, I don’t understand why you are doing this. The first example is the way to go.

Note that app.run() is correctly placed inside the main block and should remain there even if you want to use the second example.

Side note: Your two routes are not the same. The first is a route named A in the root path, and the second is a route named Index in the root path.

Related Problems and Solutions