【问题标题】:Fire Store's on_snapshot() function in Python executes twice. How to make it execute once?Python 中 Fire Store 的 on_snapshot() 函数执行两次。如何让它执行一次?
【发布时间】:2021-09-21 22:24:21
【问题描述】:

这是我在将用户添加到集合时执行的回调

# Create a callback on_snapshot function to capture changes
def on_snapshot_user(col_snapshot, changes, read_time):
    print(u'Callback received query snapshot user.')
    for change in changes:
        if change.type.name == 'ADDED':
            doc = change.document.to_dict()
            email = doc["email"]
            group = doc["survey_group"]
            gender = doc["survey_gender"]
            age = doc["survey_age"]
            userInfo = User.query.filter_by(email=email).first()
            if userInfo is None:
                User.insert(User(email))
                userInfo = User.query.filter_by(email=email).first()
            userInfo.group = group
            userInfo.gender = gender
            userInfo.age = age
            User.update(userInfo)

电子邮件是主键。当用户被添加到 Firestore 时,这会触发两次,并给出重复键的错误。 如何在 Python 中将其作为元数据执行一次。Python 尚不支持 PendingWrites? 我正在烧瓶中开发。我是新手,所以希望能提供任何帮助。

编辑: 一些上下文 - 我正在将我得到的数据添加到 PostgreSQL 数据库中。我打算这样做,因为我需要建立一种排行榜,并且我打算将用户信息 + 他们的积分存储在一个 postgreSQL 表中。

【问题讨论】:

  • 发布了答案,有用吗?

标签: python postgresql flask google-cloud-firestore


【解决方案1】:

有一些步骤可以解决多次执行问题:

1。首先是为要执行的文档创建一个文档引用变量。 为要填充的文档创建一个 doc_ref 变量。

语法:doc_ref = db.Collection(collection_name)

2。第二步是看文件。 doc_watch 将是为观看文档而创建的变量。

语法:doc_watch = doc_ref.on_snapshot_functionName(on_snapshot_functionName)

3。第三步是终止对文档的监视,以便执行一次。 您可以使用 unsubscribe() 来终止手表。

语法:doc_watch.unsubscribe()

有关 Cloud Firestore 中实时更新的更多详细信息,您可以参考文档 [1]。

[1]:https://cloud.google.com/firestore/docs/query-data/listen

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多