【问题标题】:Firebase firestore transactions and threading - pythonFirebase Firestore 事务和线程 - python
【发布时间】:2020-06-06 22:04:46
【问题描述】:

我有一个 python 脚本,它基于此处给出的示例: https://firebase.google.com/docs/firestore/manage-data/transactions

即:

transaction = db.transaction()
city_ref = db.collection(u'cities').document(u'SF')

@firestore.transactional
def update_in_transaction(transaction, city_ref):
    snapshot = city_ref.get(transaction=transaction)
    transaction.update(city_ref, {
        u'population': snapshot.get(u'population') + 1
    })

update_in_transaction(transaction, city_ref)

我找不到任何关于事务装饰器详细功能的好的文档(除了标记应该在事务中执行的内容),但似乎每当我尝试从新线程进行调用时,它都会卡住我还没有想出一个解释:

   //Works fine if called like this
   update_in_transaction(transaction, city_ref)

   //Does NOT work if called like this:
   threading.Thread(target=self.__my_method_to_start_the_transaction)

这是有问题的,因为它阻塞了我的 UI 线程并且我无法呈现任何加载指示器等。有什么建议吗?我错过了什么吗?

非常感谢!

【问题讨论】:

    标签: python multithreading firebase google-cloud-firestore


    【解决方案1】:

    我创建了一个小代码来检查来自here 的示例数据会发生什么。

    from google.cloud import firestore
    import threading
    
    db = firestore.Client()
    transaction = db.transaction()
    
    city_ref = db.collection(u'cities').document(u'LA')
    
    @firestore.transactional
    def update_in_transaction(transaction, city_ref):
        snapshot = city_ref.get(transaction=transaction)
        transaction.update(city_ref, {
            u'population': snapshot.get(u'population') + 1
        })
    
    
    x = threading.Thread(target=update_in_transaction, args=(transaction, city_ref))
    x.start()
    

    它按预期工作。在您的代码中,我认为您的工作流程更复杂,并且可能会遗漏一些东西。无论如何,如果您想了解有关装饰器的更多详细信息,这里是装饰器 transactional 的代码,它同时调用方法 _Transactional

    【讨论】:

    • 感谢您的帮助!我几乎放弃了对此的希望,是的 - 回到基础有助于找到问题的根源,我的代码中基本上有一个竞争条件,这意味着在事务进行时没有设置监听器送出。谢谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-16
    • 1970-01-01
    相关资源
    最近更新 更多