我正在尝试将Flask应用程序转换为Quart应用程序以添加异步模块并获得一些性能,如本article中所述。为此,我要使用acouchbase.Bucket对象连接到Couchbase存储桶。问题是夸脱较慢,并且在负载测试期间崩溃。这是我正在尝试的代码:
import asyncio
from quart import Quart, jsonify, g
from quart_openapi import Pint, Resource
import couchbase.experimental
couchbase.experimental.enable()
from acouchbase.bucket import Bucket
app = Pint(__name__, title = 'SomeTitle')
async def get_db():
"""
Helper function to initialize and retrive the Bucket object if not
already present.
"""
if not hasattr(g, 'cb_bucket'):
g.cb_bucket = Bucket('couchbase://localhost/bucketname', 'username', 'password')
await g.cb_bucket.connect()
return g.cb_bucket
@app.route("/apiname/<string:xId>")
class apiname(Resource):
async def get(self, xId):
cb = await get_db()
pickle_in = open('mlmodel', 'rb')
model = pickle.load(pickle_in)
y_pred_proba = model.predict_proba(Member).tolist()
return jsonify(y_pred_proba)
if __name__ == '__main__':
app.run(port = 5000, debug = True)
应用程序编译没有问题,尽管在负载测试过程中表现不佳,并在一段时间后崩溃。一个非常相似的flask应用程序(不包含任何异步模块)比quart应用程序要快,但是您希望使用async模块进行quart的速度要比flask应用程序快:
相当于烧瓶的样子:
from flask import Flask, jsonify
from flask_restplus import Api, Resource
from couchbase.cluster import Cluster
from couchbase.cluster import PasswordAuthenticator
# Coucbase connections
cluster = Cluster('couchbase://localhost/')
authenticator = PasswordAuthenticator('username', 'password')
cluster.authenticate(authenticator)
cb = cluster.open_bucket('bucketname')
app = Flask(__name__)
api = Api(app=app)
@api.route("/apiname/<string:xId>")
class apiname(Resource):
def get(self, xId):
Member = cb.get(xId)
pickle_in = open('mlmodel', 'rb')
model = pickle.load(pickle_in)
y_pred_proba = model.predict_proba(Member).tolist()
return jsonify(y_pred_proba)
if __name__ == '__main__':
app.run(port = 5000, debug = True)
这里是夸脱应用程序与烧瓶应用程序的比较。 Flask看起来比Quart应用程序快10倍,后者在测试后停止,出现此错误_ 96930细分错误。
任何答案/建议表示赞赏。
答案 0 :(得分:1)
要连接到Couchbase存储桶,您必须使用Couchbase基于角色 访问控制(RBAC)。本节将对此进行全面介绍 授权。包含用户名和密码的身份验证者, 应该定义,然后传递给集群。以下 身份验证成功后,便可以打开存储桶。
from couchbase.cluster import Cluster
from couchbase.cluster import PasswordAuthenticator
cluster = Cluster('couchbase://localhost')
authenticator = PasswordAuthenticator('username', 'password')
cluster.authenticate(authenticator)
bucket = cluster.open_bucket('bucket-name')
因此,对于您的情况,应该是这样的:
if not hasattr(g, 'cb_bucket'):
cluster = Cluster('couchbase://localhost')
authenticator = PasswordAuthenticator('username', 'password')
cluster.authenticate(authenticator)
bucket = await cluster.open_bucket('bucket-name')
return bucket