首页 > 解决方案 > Firebase Python SDK 发生的阻塞是否有解决方法?喜欢添加完成回调?

问题描述

最近,我将 express.js 中的 REST 服务器代码移至使用 FastAPI。到目前为止,直到最近,我都成功地完成了过渡。我注意到基于 firebase python admin sdk 文档,与 node.js 不同,python sdk 是阻塞的。文档在这里说:

在 Python 和 Go Admin SDK 中,所有写入方法都是阻塞的。也就是说,在写入提交到数据库之前,写入方法不会返回。

我认为这个功能对我的代码有一定的影响。这也可能是我构建代码的方式。我的一个文件中的一些代码如下:

from app.services.new_service import nService
from firebase_admin import db
import json
import redis

class TryNewService:
  async def tryNew_func(self, request):
    # I've already initialized everything in another file for firebase
    ref = db.reference()
    r = redis.Redis()
    holdingData = await nService().dialogflow_session(request)
    fulfillmentText = json.dumps(holdingData[-1])
    body = await request.json()

    if ("user_prelimInfo_address" in holdingData):
      holdingData.append("session")
      holdingData.append(body["session"])
      print(holdingData)
      return(holdingData)
    else:
      if (("Default Welcome Intent" in holdingData)):
        pass
      else:
        UserVal = r.hget(name='{}'.format(body["session"]), key="userId").decode("utf-8")
        ref.child("users/{}".format(UserVal)).child("c_data").set({holdingData[0]:holdingData[1]})
        print(holdingData)
      return(fulfillmentText)

ref.set()在我的代码中使用 line的阻塞效果有什么解决方法吗?有点像在 node.js 中添加回调?我是 python 3 的 asyncio 世界的新手。


截至 2020 年 6 月 13 日更新:所以我添加了以下代码,现在我得到了一个RuntimeError: Task attached to a different loop. 在我的第二个 else 语句中,我执行以下操作:

loop = asyncio.new_event_loop()
UserVal = r.hget(name='{}'.format(body["session"]), key="userId").decode("utf-8")
with concurrent.futures.ThreadPoolExecutor(max_workers=20) as pool:
  result = await loop.run_in_executor(pool, ref.child("users/{}".format(UserVal)).child("c_data").set({holdingData[0]:holdingData[1]}))
  print("custom thread pool:{}".format(result))

有了这个新的 RuntimeError,我将不胜感激。

标签: python-3.xfirebasefirebase-realtime-databasepython-asynciofirebase-admin

解决方案



推荐阅读