【问题标题】:Using additional command line arguments with gunicorn在 gunicorn 中使用额外的命令行参数
【发布时间】:2012-01-19 16:33:00
【问题描述】:

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

例如,我可以在我的 Flask 应用程序中包含并解析 foo 选项吗?

gunicorn mypackage:app --foo=bar

谢谢,

【问题讨论】:

    标签: python flask gunicorn


    【解决方案1】:

    我通常把它放在__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 中的参数。

    【讨论】:

      【解决方案2】:

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

      $ 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))..
      猜你喜欢
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2021-06-02
      • 1970-01-01
      • 2019-11-04
      • 1970-01-01
      • 2014-08-03
      • 2023-02-23
      相关资源
      最近更新 更多