Instalação
pip install google-cloud-firestore
Uso
Exemplo adicionando um registro e ouvindo mudanças
import time
import random
from google.cloud import firestore
# The `project` parameter is optional and represents which project the client
# will act on behalf of. If not supplied, the client falls back to the default
# project inferred from the environment.
db = firestore.Client(project="my-project")
# gen random number
random = random.randint(0, 1000)
data = {"name": "Los Angeles " + str(random), "state": "CA", "country": "USA"}
# Add a new doc in collection 'cities' with ID 'LA'
db.collection("cities").document("LA").set(data)
def init():
def on_snapshot(col_snapshot, changes, read_time):
for change in changes:
if change.type.name == 'ADDED':
print(f'New record: {change.document.id}', change.document.to_dict())
elif change.type.name == 'MODIFIED':
print(f'Modified record: {change.document.id}', change.document.to_dict())
elif change.type.name == 'REMOVED':
print(f'Removed record: {change.document.id}', change.document.to_dict())
col_ref = db.collection('cities')
print("watching...")
# Watch the collection query
query_watch = col_ref.on_snapshot(on_snapshot)
# Wait for 60 seconds
time.sleep(60)
print('Watched...')
# Stop watching
query_watch.unsubscribe()
if __name__ == '__main__':
init()
Adicionando documento sem ID
update_time, city_ref = db.collection("cities").add(city)
print(f"Added document with id {city_ref.id}")