Google Firebase: Get, update or create documents using Python

混江龙づ霸主 提交于 2019-12-04 15:31:41

Another night and I can answer myself (thanks to Doug for the hint in the discussion):

The problem for me was that there are two similar documentations (for Python part, the 2nd one is more extensive than just Python). I found the first one more helpful, but sometimes I needed to use part of the second one, too:

1) Accessing the documents:

import firebase_admin
from firebase_admin import credentials, firestore
databaseURL = {
     'databaseURL': "https://test-6f02d.firebaseio.com"
}
cred = credentials.Certificate("test.json")
firebase_admin.initialize_app(cred, databaseURL)

database = firestore.client()
col_ref = database.collection('items') # col_ref is CollectionReference
results = col_ref.where('name', '==', 'Pepa').get() # one way to query
results = col_ref.order_by('date',direction='DESCENDING').limit(1).get() # another way - get the last document by date
for item in results:
    print(item.to_dict())
    print(item.id)
# item is DocumentSnapshot
# note: the documentation says get() is depreciated in favour of stream(), however stream() did not work for me

2) Still do not know, but I do not need it as 1) works ok.

3) Update or create document:

# Continuing from 1)

# Udpdate:
doc = col_ref.document(item.id) # doc is DocumentReference
field_updates = {"description": "Updated description"}
doc.update(field_updates)

# Create:
import datetime
new_values = {
    "name": "Newbie",
    "description": "Shiny New Document",
    "date": datetime.datetime.now()
}
col_ref.document().create(new_values)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!