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

孤街浪徒 提交于 2019-11-26 11:35:01

问题


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__\'

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



来源:https://stackoverflow.com/questions/15156758/flask-gunicorn-app-cant-get-name-to-equal-main

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!