10

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__'
Paco
  • 4,520
  • 3
  • 29
  • 53
Johnston
  • 20,196
  • 18
  • 72
  • 121

1 Answers1

16

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

Sean Vieira
  • 155,703
  • 32
  • 311
  • 293
  • 1
    So it will never be "__main__". That totally makes sense now. – Johnston Mar 03 '13 at 12:49
  • So how to keep __main__ when running python and still make it work with gunicorn ? – user2396640 Jul 11 '22 at 19:53
  • Just use the pattern the question uses - guard your `main` with an `if __name__ == '__main__':` and tell gunicorn what the name of your object is. Gunicorn _imports_ your app and wraps it, so it needs to be able to treat your module as a _library_ (while you want it to run as an **application** when you run `python your_app.py`). – Sean Vieira Jul 18 '22 at 02:14