【发布时间】:2012-01-19 16:33:00
【问题描述】:
假设我根据http://gunicorn.org/deploy.html#runit 在 gunicorn 下启动 Flask 应用程序,有没有办法让我包含/解析/访问其他命令行参数?
例如,我可以在我的 Flask 应用程序中包含并解析 foo 选项吗?
gunicorn mypackage:app --foo=bar
谢谢,
【问题讨论】:
假设我根据http://gunicorn.org/deploy.html#runit 在 gunicorn 下启动 Flask 应用程序,有没有办法让我包含/解析/访问其他命令行参数?
例如,我可以在我的 Flask 应用程序中包含并解析 foo 选项吗?
gunicorn mypackage:app --foo=bar
谢谢,
【问题讨论】:
我通常把它放在__init.py__main()之后,然后我可以在有或没有gunicorn的情况下运行(假设你的main()也支持其他功能)。
# __init__.py
# Normal entry point
def main():
...
# Gunicorn entry point generator
def app(*args, **kwargs):
# Gunicorn CLI args are useless.
# https://stackoverflow.com/questions/8495367/
#
# Start the application in modified environment.
# https://stackoverflow.com/questions/18668947/
#
import sys
sys.argv = ['--gunicorn']
for k in kwargs:
sys.argv.append("--" + k)
sys.argv.append(kwargs[k])
return main()
这样你就可以简单地运行例如
gunicorn 'app(foo=bar)' ...
您的main() 可以使用标准代码,该代码需要sys.argv 中的参数。
【讨论】:
您不能直接传递命令行参数,但您可以轻松地选择应用程序配置。
$ gunicorn 'mypackage:build_app(foo="bar")'
将按预期调用传递 foo="bar" kwarg 的函数“build_app”。然后,此函数应返回将要使用的 WSGI 可调用对象。
【讨论】:
(foo="bar", foo1="bar1")
gunicorn>=20 中不起作用,您将收到Failed to find application object 'build_app(foo="there")' in 'mypackage' 错误。见github.com/benoitc/gunicorn/issues/2159
-n xyz-app) 并用作标识符 (import sys, re; appid = re.search(r'\-n\s{1,}([^\s|$]+)', ''.join(sys.argv)).group(1))..