Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flask Gunicorn app can't get __name__ to equal '__main__'

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__'
like image 955
Johnston Avatar asked Mar 01 '13 11:03

Johnston


1 Answers

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__".

like image 93
Sean Vieira Avatar answered Oct 31 '22 14:10

Sean Vieira