简体   繁体   English

Flask Gunicorn 应用程序无法让 __name__ 等于 '__main__'

[英]Flask Gunicorn app can't get __name__ to equal '__main__'

I have this from /home/myname/myapp/app.py :我从/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 .所以应用app__name__app Not __main__ like I need it to be to run the if statement.不是__main__就像我需要它来运行 if 语句。
I tried putting an empty __init__.py in the directory.我尝试在目录中放置一个空的__init__.py Here is my nginx sites-enabled default :这是我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. ...当我访问该网站时,该应用程序确实会打印'Hello world' The point is that I need __name__ to equal '__main__' . 关键是我需要__name__等于'__main__' I also just want to know why it doesn't and how to make it equal __main__ . 我也只是想知道为什么不这样做以及如何使它等于__main__

Edit 2编辑 2

... I just had the epiphany that I do not need to run app.run() since that is what Gunicorn is for. ...我突然意识到我不需要运行app.run()因为那是app.run()用途。 Duh. 呃。 But I would still like to figure out why __name__ isn't '__main__' 但我仍然想弄清楚为什么__name__不是'__main__'

Python sets __name__ to "__main__" when the script is the entry point for the Python interpreter.当脚本是 Python 解释器的入口点时,Python 将__name__设置为"__main__" 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__" .由于 Gunicorn 导入了它正在运行的脚本,脚本将不是入口点,因此不会将__name__设置为"__main__"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM