Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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? Am I missing something?

Many thanks!

like image 341
John Lane Avatar asked Sep 10 '26 03:09

John Lane


1 Answers

I created a little code to check what could be going on with the sample data from 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()

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.

like image 170
Ferregina Pelona Avatar answered Sep 12 '26 17:09

Ferregina Pelona



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!