使用额外的命令行参数启动gunicorn
假设我在用gunicorn启动一个Flask应用,参考了这个链接 http://gunicorn.org/deploy.html#runit,有没有办法让我在命令行中添加、解析或访问额外的参数呢?
比如,我能不能在我的Flask应用中以某种方式包含并解析foo
这个选项呢?
gunicorn mypackage:app --foo=bar
谢谢,
2 个回答
13
我通常把它放在 __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
中的参数。
41
你不能直接传递命令行参数,但你可以很简单地选择应用程序的配置。
$ gunicorn 'mypackage:build_app(foo="bar")'
这段代码会调用名为“build_app”的函数,并传递一个叫做foo的参数,值是“bar”。这个函数应该会返回一个可以用的WSGI对象。