如何从Flask(Quart)应用程序与couchbase服务器建立异步连接?

问题描述 投票:2回答:1

我正在尝试将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等效物如下所示:

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 segmentation fault_。

夸脱:Quart APP烧瓶:Flask

任何答案/建议表示赞赏。

python asynchronous couchbase python-asyncio quart
1个回答
1
投票

我认为你将BucketCluster混合在一起。

来自CouchBase documentation

要连接到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
© www.soinside.com 2019 - 2024. All rights reserved.