使用与gunicorn的其他命令行参数

sho*_*app 19 python flask gunicorn

假设我按照http://gunicorn.org/deploy.html#runit在gunicorn下启动Flask应用程序,有没有办法让我包含/解析/访问其他命令行参数?

例如,我可以foo以某种方式在Flask应用程序中包含和解析选项吗?

gunicorn mypackage:app --foo=bar
Run Code Online (Sandbox Code Playgroud)

谢谢,

Pau*_*vis 30

您不能直接传递命令行参数,但可以轻松地选择应用程序配置.

$ gunicorn 'mypackage:build_app(foo="bar")'
Run Code Online (Sandbox Code Playgroud)

将按预期调用函数"build_app"传递foo ="bar"kwarg.然后,此函数应返回将使用的WSGI可调用对象.

  • 请注意,这在“gunicorn>=20”中不起作用,您将收到“无法在“mypackage”中找到应用程序对象“build_app(foo =“there”)”错误。请参阅 https://github.com/benoitc/gunicorn/issues/2159 (5认同)
  • 谢谢!在搜索如何传递多个参数时到达此处.结果就像将它们作为逗号分隔值传递一样简单; 例如`(foo ="bar",foo1 ="bar1")` (3认同)

per*_*oud 8

我通常把它放在__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.
    # /sf/ask/594675721/
    #
    # Start the application in modified environment.
    # /sf/ask/1306826321/
    #
    import sys
    sys.argv = ['--gunicorn']
    for k in kwargs:
        sys.argv.append("--" + k)
        sys.argv.append(kwargs[k])
    return main()
Run Code Online (Sandbox Code Playgroud)

这样你就可以简单地使用例如

gunicorn 'app(foo=bar)' ...
Run Code Online (Sandbox Code Playgroud)

并且您main()可以使用需要sys.argv.