简体   繁体   English

Firebase 防火墙事务和线程 - python

[英]Firebase firestore transactions and threading - python

I have a python script, which is based on the examples given here: https://firebase.google.com/docs/firestore/manage-data/transactions我有一个 python 脚本,它基于此处给出的示例: https://firebase.google.com/docs/firestore/manage-data/transactions

Namely:即:

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)

I can't find any good documentation on what the transactional decorator does in detail (other than mark what should be executed in the transaction), but it seems whenever I try to make the call from a new thread, it seizes up and I haven't been able to come up with an explanation:我找不到任何关于事务装饰器详细功能的好的文档(除了标记应该在事务中执行的内容),但似乎每当我尝试从新线程进行调用时,它就会卡住并且我没有无法想出一个解释:

   //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)

It's problematic, since it is blocking my UI thread and I can't render any loading indicators, etc. Any suggestions?这是有问题的,因为它阻塞了我的 UI 线程并且我无法呈现任何加载指示器等。有什么建议吗? Am I missing something?我错过了什么吗?

Many thanks!非常感谢!

I created a little code to check what could be going on with the sample data fromhere .我创建了一个小代码来检查这里的示例数据可能会发生什么。

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()

And it worked as expected.它按预期工作。 In your code I think you have a more complex workflow and maybe there could be missing something.在您的代码中,我认为您的工作流程更复杂,并且可能会遗漏一些东西。 Anyway if you want more details about the decorator, here is the code for the decorator transactional which at the same time calls the method _Transactional .无论如何,如果您想了解有关装饰器的更多详细信息,这里是装饰器transactional的代码,它同时调用方法_Transactional

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM