import datetime
from threading import Timer
import firebase_admin
from firebase_admin import firestore
import calendar
db = firestore.Client()
col_ref = db.collection(u'tblAssgin').get()
current_serving = [doc.id for doc in col_ref]
#print(current_serving)
def sit_time():
for i in current_serving:
try:
doc_ref = db.collection(u'tblAssgin').document(i)
except:
current_serving.remove(doc_ref)
else:
doc = doc_ref.get()
a = doc.get('assginTime')
assign_time = datetime.datetime.fromtimestamp(calendar.timegm(a.timetuple()))
now = datetime.datetime.now()
sitting_time = now - assign_time
hours,remainder = divmod(sitting_time.seconds, 3600)
minutes, seconds = divmod(remainder, 60)
print('minutes:',minutes)
updates = {u'sitting_time':minutes}
doc_ref.update(updates)
t = None
def refresh():
global t
sit_time()
t = Timer(60, refresh)
t.daemon = True
t.start()
refresh()
所以基本上上面的代码确实它首先获取集合名称'tblAssgin'的所有文档id并将其存储在'current_serving'列表中。然后,循环遍历每个文档并计算时间并在每60秒后再次运行。现在假设我删除了一个文档,然后找不到该文档。因此,我想在未找到文档时执行此操作,引发异常,并从“current_serving”列表中删除该文档ID。但是没有抓住这个例外。
请帮忙
提前致谢.. !!
答案 0 :(得分:1)
如果文档不存在,您假设CollectionReference.document()
会抛出异常。它没有。
>>> client.collection('non-existing').document('also-non-existing')
<google.cloud.firestore_v1beta1.document.DocumentReference object at 0x10feac208>
但如果文档不存在,DocumentReference.get()
将抛出异常。
>>> client.collection('non-existing').document('also-non-existing').get()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "~/gae/lib/python3.6/site-packages/google/cloud/firestore_v1beta1/document.py", line 432, in get
raise exceptions.NotFound(self._document_path)
google.api_core.exceptions.NotFound: 404 ~/databases/(default)/documents/non-existing/also-non-existing