我正在使用 Flask 的内置开发服务器开发 Flask 应用程序。我使用 Flask-Script 启动它。我想切换到使用 Gunicorn 作为 Web 服务器。为此,我是否需要在 Flask-Script 和 Gunicorn 之间编写某种集成代码?或者 Flask-Script 与使用 Gunicorn 运行应用程序无关?
提前致谢!
给@sean-lynch 的道具。以下是根据他的回答工作的、经过测试的代码。我所做的更改是:
sys.argv
在remove_non_gunicorn_command_line_args()
尝试启动服务器之前,将删除 Gunicorn 无法识别的选项。否则 Gunicorn 会抛出错误,并显示如下消息:error: unrecognized arguments: --port 5010
. 我删除-p
是因为,即使它不会导致错误,那只是因为 Gunicorn 认为它是其pidfile
选项的简短形式,这显然不是预期的。修改 GunicornServer.handle() 签名以匹配它覆盖的方法,即 Command.handle()
-
from flask_script import Command
from gunicorn.app.base import Application
class GunicornServer(Command):
description = 'Run the app within Gunicorn'
def __init__(self, host='127.0.0.1', port=8000, workers=6):
self.port = port
self.host = host
self.workers = workers
def get_options(self):
return (
Option('-t', '--host',
dest='host',
default=self.host),
Option('-p', '--port',
dest='port',
type=int,
default=self.port),
Option('-w', '--workers',
dest='workers',
type=int,
default=self.workers),
)
def handle(self, app, *args, **kwargs):
host = kwargs['host']
port = kwargs['port']
workers = kwargs['workers']
def remove_non_gunicorn_command_line_args():
import sys
args_to_remove = ['--port','-p']
def args_filter(name_or_value):
keep = not args_to_remove.count(name_or_value)
if keep:
previous = sys.argv[sys.argv.index(name_or_value) - 1]
keep = not args_to_remove.count(previous)
return keep
sys.argv = filter(args_filter, sys.argv)
remove_non_gunicorn_command_line_args()
from gunicorn import version_info
if version_info < (0, 9, 0):
from gunicorn.arbiter import Arbiter
from gunicorn.config import Config
arbiter = Arbiter(Config({'bind': "%s:%d" % (host, int(port)),'workers': workers}), app)
arbiter.run()
else:
class FlaskApplication(Application):
def init(self, parser, opts, args):
return {
'bind': '{0}:{1}'.format(host, port),
'workers': workers
}
def load(self):
return app
FlaskApplication().run()
manager.add_command('gunicorn', GunicornServer())