Reputation: 3977
I have a Flask application setup on my linode with a directory structure like so:
|--------flask-test
|----------------app
|-----------------------static
|-----------------------templates
|-----------------------venv
|-----------------------__init__.py
|-----------------------main.py
my __init__.py
is:
# __init__.py
from flask import Flask
from main import main
app = Flask(__name__)
app.register_blueprint(main)
app.run()
and main.py
like so:
# main.py
from flask import Blueprint
main = Blueprint('main',__name__)
@main.route("/")
def hello():
return "Hello World!"
@main.route("/england/")
def england():
return "Hello England!"
If I run the app locally there are no issues. If I go to my server address in the web browser I get an internal server error. However if I remove the line: app.run
from __init__.py
it works fine. Why is this? Why do I not need the run method?
Upvotes: 5
Views: 3314
Reputation: 19319
You should do
if __name__ == '__main__':
app.run()
The reason is that Apache or NGINX or some other web server loads your app directly on the server but app.run()
runs flask's internal web-server so you can test your app.
EDIT: Since someone came by and upvoted this very old answer (thanks!) I will point out that there is no reason to include this convention. Flask includes a run command for testing.
Instead of the old way:
python yourapp.py
you now do:
flask --app yourapp run
Or if you name the main controller of your app "app.py" you can commit the --app
flag.
Upvotes: 10
Reputation: 58563
It is a bit odd to have app.run()
inside of the __init__.py
file, normally it would be in a separate application script you run, where it would be written as:
if __name__ == '__main__':
app.run()
This way app.run()
is only called when that script is executed as the application.
This is necessary because you do not want app.run()
called when hosting under a WSGI server such as mod_wsgi or gunicorn. When using such WSGI servers, even if reusing the same script file as holder of the WSGI application entrypoint, __name__
wouldn't be set to __main__
but the basename of the script file. This ensures that app.run()
isn't called where it is the separate WSGI server which is running the web server component.
Upvotes: 5