在gunicorn 中使用额外的命令行参数

发布于 2024-12-20 20:19:27 字数 288 浏览 3 评论 0原文

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

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

gunicorn mypackage:app --foo=bar

谢谢,

Assuming I'm starting a Flask app under gunicorn as per http://gunicorn.org/deploy.html#runit, is there a way for me to include/parse/access additional command line arguments?

E.g., can I include and parse the foo option in my Flask application somehow?

gunicorn mypackage:app --foo=bar

Thanks,

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

呆头 2024-12-27 20:19:27

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

$ gunicorn 'mypackage:build_app(foo="bar")'

将调用函数“build_app”并按预期传递 foo="bar" kwarg。然后,该函数应返回将使用的 WSGI 可调用函数。

You can't pass command line arguments directly but you can choose application configurations easily enough.

$ gunicorn 'mypackage:build_app(foo="bar")'

Will call the function "build_app" passing the foo="bar" kwarg as expected. This function should then return the WSGI callable that'll be used.

撩人痒 2024-12-27 20:19:27

我通常把它放在 main() 之后的 __init.py__ 中,然后我可以在有或没有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()

这样您就可以简单地使用eg 运行,

gunicorn 'app(foo=bar)' ...

并且您的main() 可以使用需要sys.argv 中的参数的标准代码。

I usually put it in __init.py__ after main() and then I can run with or without gunicorn (assuming your main() supports other functions too).

# __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()

That way you can run simply with e.g.

gunicorn 'app(foo=bar)' ...

and your main() can use standard code that expects the arguments in sys.argv.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文