如何通过编程方式将可调用对象传递给Gunicorn,而不是参数

时间:2019-11-21 22:00:24

标签: python python-3.x gunicorn

我有以下实现方式,可以使用gunicorn启动网络应用程序

@click.command("run_app", help="starts application in gunicorn")
def run_uwsgi():
    """
    Runs the project in gunicorn
    """

    import sys

    sys.argv = ["--gunicorn"]

    sys.argv.append("-b 0.0.0.0:5000")
    sys.argv.append("myapp.wsgi:application")

    WSGIApplication(usage="%(prog)s [OPTIONS] [APP_MODULE]").run()

这将使用gunicorn启动应用程序,根据要求如何在不使用参数的情况下启动应用程序?有没有一种方法可以为gunicorn分配sys.argv值?

1 个答案:

答案 0 :(得分:0)

我想发布我已经解决的解决方案

@click.command("uwsgi", help="starts application in gunicorn")
def run_uwsgi():
    """
    Runs the project in gunicorn
    """
    from gunicorn.app.base import Application

    import sys

    class MyApplication(Application):
        """
        Bypasses the class `WSGIApplication` and made it 
        independent from command line arguments
        """
        def init(self, parser, opts, args):

            self.cfg.set("default_proc_name", args[0])

            # Added this to ensure the application integrity
            self.app_uri = "myapp.wsgi:application"

        def load_wsgiapp(self):
            # This would do the trick
            # returns application callable
            return application

        def load(self):
            return self.load_wsgiapp()

    sys.argv = ["--gunicorn"]

    sys.argv.append(f"-b {os.environ['APP_HOST']}:{os.environ['APP_PORT']}")

    # Throws an error if this is missing.
    sys.argv.append("myapp.wsgi:application")

    MyApplication(usage="%(prog)s [OPTIONS] [APP_MODULE]").run()

我直接从

返回可调用对象
def load_wsgiapp(self):
    # This would do the trick
    # returns application callable
    return application

wsgi.py

application = main.create_app()

但是仍然需要为模块传递命令行参数,否则会引发错误。 如果您使用Nuitka捆绑应用程序,则可以将其旋转并与gunicorn一起使用。