【问题标题】:Flask Gunicorn app can't get __name__ to equal '__main__'Flask Gunicorn 应用程序无法让 __name__ 等于 '__main__'
【发布时间】:2013-02-15 21:31:14
【问题描述】:

我有这个来自/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()

当我跑步时:

$ gunicorn app:app -b 127.0.0.2:8000

上面写着:

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

所以应用程序的__name__app。不像__main__ 那样我需要它来运行 if 语句。
我尝试在目录中放置一个空的__init__.py。这是我的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;
        }
}

编辑

...当我访问该网站时,此应用确实打印'Hello world'。关键是我需要__name__ 等于'__main__'。我也只是想知道为什么它不等于__main__

Edit 2

... 我只是顿悟了,我不需要运行app.run(),因为这就是 Gunicorn 的用途。呃。但我仍然想弄清楚为什么__name__ 不是'__main__'

【问题讨论】:

  • 你为什么需要它?当您使用guincorn 运行它时,请尝试访问http://127.0.0.2:8000/

标签: python nginx flask gunicorn


【解决方案1】:

当脚本是 Python 解释器的入口点时,Python 将 __name__ 设置为 "__main__"。由于 Gunicorn 导入它正在运行的脚本脚本将不是入口点,因此不会将 __name__ 设置为 "__main__"

【讨论】:

  • 所以它永远不会是“main”。现在这完全有道理。
猜你喜欢
  • 2011-01-15
  • 2016-07-20
  • 2011-06-09
  • 1970-01-01
  • 2016-04-22
  • 2015-11-13
  • 1970-01-01
相关资源
最近更新 更多