I have this from /home/myname/myapp/app.py:
from flask import Flask
app = Flask(__name__)
print __name__
@app.route('/')
def index():
return "Hello world!"
if __name__ == '__main__':
print 'in if'
app.run()
When I run:
$ gunicorn app:app -b 127.0.0.2:8000
It says:
2013-03-01 11:26:56 [21907] [INFO] Starting gunicorn 0.17.2 2013-03-01 11:26:56 [21907] [INFO] Listening at: http://127.0.0.2:8000 (21907) 2013-03-01 11:26:56 [21907] [INFO] Using worker: sync 2013-03-01 11:26:56 [21912] [INFO] Booting worker with pid: 21912 app
So the __name__ of the app is app. Not __main__ like I need it to be to run the if statement.
I tried putting an empty __init__.py in the directory. Here is my nginx sites-enabled default:
server {
#listen 80; ## listen for ipv4; this line is default and implied
#listen [::]:80 default_server ipv6only=on; ## listen for ipv6
root /home/myname/myapp;
# Make site accessible from http://localhost/
server_name localhost;
location / {
proxy_pass http://127.0.0.2:8000;
}
}
Edit
… While this app does print 'Hello world' when I visit the site. The point is that I need __name__ to equal '__main__'. I also just want to know why it doesn’t and how to make it equal __main__.
Edit 2
… I just had the epiphany that I do not need to run app.run() since that is what Gunicorn is for. Duh. But I would still like to figure out why __name__ isn’t '__main__'
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
Python sets __name__ to "__main__" when the script is the entry point for the Python interpreter. Since Gunicorn imports the script it is running that script will not be the entry point and so will not have __name__ set to "__main__".
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0