Reputation: 33
I'm using Gunicorn on Heroku to try to serve a basic webpage, and if I use the normal route decorator it works fine. 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 serve 'b' at the index. However, if instead of using the route decorator I use the add_url_route function, it only responds 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's my Procfile:
web: gunicorn test:app --log-file=-
It's worth noting that when I run this from the command line with Python (python test.py), both work normally. Am I doing something wrong here? I'm using Python 3.6.3 and Flask 0.12.2.
Upvotes: 3
Views: 678
Reputation: 5458
The app.add_url_rule
line is only executed when you directly run the python script. When you just import the script (this is what gunicorn does) then no routes are configured at all and any request will result in a 404
.
This also explains why both versions worked for you when executing locally.
If you really want to you could move the app.add_url_rule
outside of the main block. I don't see why you would want to do that however. 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 your second example.
A side note: your two routes are not identical. The first one is a route called a
at the root path and your second one is a route called index
at the root path.
Upvotes: 3