【问题标题】:Pass command line parameters to uwsgi script将命令行参数传递给 uwsgi 脚本
【发布时间】:2014-03-08 06:40:51
【问题描述】:

我正在尝试将参数传递给示例 wsgi 应用程序,:

config_file = sys.argv[1]

def application(env, start_response):
    start_response('200 OK', [('Content-Type','text/html')])
    return [b"Hello World %s" % config_file]

然后运行:

uwsgi --http :9090 --wsgi-file test_uwsgi.py  -???? config_file # argument for wsgi script

有什么聪明的方法可以实现吗?在 uwsgi 文档中找不到它。也许还有另一种方法可以为 wsgi 应用程序提供一些参数? (环境变量超出范围)

【问题讨论】:

    标签: python wsgi uwsgi


    【解决方案1】:

    python 参数:

    --pyargv "foo bar"

    sys.argv
    ['uwsgi', 'foo', 'bar']
    

    uwsgi 选项:

    --set foo=bar

    uwsgi.opt['foo']
    'bar'
    

    【讨论】:

    • 你的sys.argv不应该是['uwsgi', 'foo', 'bar']吗?
    • --pyargv "foo bar" 也可以很好地与argparse 配合使用。
    【解决方案2】:

    您可以使用带有@roberto 提到的pyargv 设置的.ini 文件。让我们调用我们的配置文件uwsgi.ini 并使用内容:

    [uwsgi]
    wsgi-file=/path/to/test_uwsgi.py
    pyargv=human
    

    然后让我们创建一个 WGSI 应用来测试它:

    import sys
    def application(env, start_response):
        start_response('200 OK', [('Content-Type','text/html')])
        return [str.encode("Hello " + str(sys.argv[1]), 'utf-8')]
    

    你可以看到如何加载这个文件https://uwsgi-docs.readthedocs.io/en/latest/Configuration.html#loading-configuration-files

     uwsgi --ini /path/to/uwsgi.ini --http :8080
    

    然后当我们curl 应用程序时,我们可以看到我们的参数回显:

    $ curl http://localhost:8080
    Hello human
    

    如果您尝试将 argparse 样式参数传递给您的 WSGI 应用程序,它们在 .ini 中也可以正常工作:

    pyargv=-y /config.yml
    

    【讨论】:

      【解决方案3】:

      我最终使用了一个环境变量,但在启动脚本中设置了它:

      def start(uwsgi_conf, app_conf, logto):
          env = dict(os.environ)
          env[TG_CONFIG_ENV_NAME] = app_conf
          command = ('-c', uwsgi_conf, '--logto', logto, )
          os.execve(os.path.join(distutils.sysconfig.get_config_var('prefix'),'bin', 'uwsgi'), command, env)
      

      【讨论】:

        猜你喜欢
        • 2013-10-22
        • 2016-12-19
        • 1970-01-01
        • 2013-10-11
        • 1970-01-01
        • 2018-10-16
        • 1970-01-01
        • 1970-01-01
        • 2020-05-09
        相关资源
        最近更新 更多