我有一个连接到 Cassandra 的 Flask 应用程序。当我在 Gunicorn 下运行此应用程序并将 Gunicorn 作为烧瓶脚本命令调用python manage.py gunicorn
时,它会挂起。但是当我在命令行上运行同一个应用程序时gunicorn manage:app
,它成功了。为什么?
问问题
807 次
1 回答
3
解释
Gunicorn 分叉工人来处理传入的请求。如果 Cassandra 会话(连接池)是在工人分叉之前创建的(例如,在使用应用程序工厂模式创建应用程序期间),工人在使用 Cassandra 时会遇到问题。DataStax 建议每个工作人员都有自己的会话,因此您需要将会话创建推迟到分叉之后。当您将 Gunicorn 和 Flask 作为自定义应用程序捆绑在一起时,这是一个问题,但大概在命令行上,Gunicorn 显然可以在创建 Flask 应用程序之前完全初始化和分叉。
例子
要查看这两种行为,请将 bad=False 手动更改为 bad=True。
from cassandra.cluster import Cluster
from flask import Flask
from flask_script import Command, Manager
from gunicorn.app.base import BaseApplication
from gunicorn.six import iteritems
class CassandraClient:
def __init__(self, bad=False):
self.session = None
self.cluster = None
if bad:
self.connect()
def connect(self):
self.cluster = Cluster(['127.0.0.1'])
self.session = self.cluster.connect('keyspace')
def execute(self):
if not self.session:
self.connect()
query = '''
select now()
from system.local
'''
return self.session.execute(query)[0]
class GunicornApp(BaseApplication):
'''
Bundle Gunicorn and Flask together, so that we can call it as a
flask-script command.
http://docs.gunicorn.org/en/stable/custom.html
'''
def __init__(self, app, options=None):
self.options = options or {}
self.application = app
super(GunicornApp, self).__init__()
def load_config(self):
config = dict(
[(key, value) for key, value in iteritems(self.options)
if key in self.cfg.settings and value is not None])
for key, value in iteritems(config):
self.cfg.set(key.lower(), value)
def load(self):
return self.application
class GunicornCommand(Command):
'''
Modeled off of flask_script.Server
'''
def __init__(self, app, options):
self.app = app
self.options = options
def __call__(self, *args, **kwargs):
GunicornApp(self.app, self.options).run()
app = Flask(__name__)
app.cassandra = CassandraClient()
@app.route('/')
def hello():
return str(app.cassandra.execute())
if __name__ == '__main__':
manager = Manager(app)
gunicorn_options = {
'bind': '127.0.0.1',
'port': 8000,
'workers': 4
}
manager.add_command("gunicorn", GunicornCommand(app, gunicorn_options))
manager.run()
版本
Flask==0.12.1
Flask-Script==2.0.5
gunicorn==19.7.1
cassandra-driver==3.8.1
参考
于 2017-04-22T01:58:18.877 回答