python-3.x - 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,我将不胜感激。
解决方案
使用ThreadPoolExecutor
. 见https://medium.com/@hiranya911/firebase-python-admin-sdk-with-asyncio-d65f39463916
推荐阅读
- python - 在 Django 中聚合一个窗口查询集
- php - 在重力形式隐藏字段中保存自定义帖子类型标题
- html - 名称组件导航,包括我当前的位置菜单
- pine-script - 当价格越过它们时线被切断
- azure - 在注册/登录用户流中从我的 API 连接器返回的 JWT 令牌中未显示自定义值
- excel - VBA通过函数传递范围
- python - Fastapi OAuth2PasswordRequestForm - 在验证表单中添加自定义字段“rentalpoint”
- django - 优雅重启 django-q qcluster
- spring-boot - JMX 中的 Atomikos 5.0.6 连接池设置
- reactjs - 为什么图标“汽车”不能在 svg 中跟随“路径”移动?