【发布时间】:2021-05-03 16:35:04
【问题描述】:
我正在尝试在 Firestore 中将文档从一个集合“移动”到另一个集合。这意味着复制/粘贴文档,然后删除原件。我正在尝试使用 Python 实现这个服务器端。
我知道我应该使用事务,所以我实现了一个。当我运行脚本时,我可以在 Firestore 中看到我所针对的文档确实已从旧集合中删除,并且已在新集合中创建了一个新文档。
成功了吗?
如何测试我编码的交易?我对事务逻辑本身有点困惑。特别是,我不确定我是如何在我的事务中实现“复制部分”的(见下文)。为什么 get() 和 delete() 有事务的引用而 set() 没有?
到目前为止,这是我的代码,使用事务来移动文档:
from google.cloud import firestore
import time
@firestore.transactional
def move_in_transaction(transaction, doc1, doc2):
# get the data
doc = doc1.get(transaction=transaction)
if doc.exists:
print(f'Document data: {doc.to_dict()}')
else:
print(u'No such document!')
# copy the data
doc2.set(doc.to_dict())
# delete the original
transaction.delete(doc.reference)
def main():
db = firestore.Client()
transaction = db.transaction()
doc1 = db.collection(u'AAA').document(u'111')
doc2 = db.collection(u'BBB').document(u'111')
transaction_attempts = 0
while True:
try:
# apply transaction
move_in_transaction(transaction, doc1, doc2)
print("Successfully applied transaction")
break
except Exception as e:
print(f"Could not apply transaction. Error: {e}")
time.sleep(5)
transaction_attempts += 1
if transaction_attempts > 10:
print(f"Stop trying transactions")
exit()
它完成了这项工作,但我不确定事务本身中的“复制部分”。
【问题讨论】:
标签: python firebase google-cloud-firestore