Mohamed Nashaat
Mohamed Nashaat

Reputation: 100

Firestore Listeners for python

I want to know a way to listen to any changes that happen in a document in Firestore like adding a new document or deleting a document. But I can't find any relevant documentation regarding this matter so please if anyone used this before post the code snippets to help me.

To overcome this problem I have made an infinite loop to check if there are any changes every second but after about 15 minutes if gets me an error too many requests

Edit

After using the On snapshot listener my application just doesn't do anything it just runs with no errors and then terminates and below the code, I have used.

import firebase_admin
from firebase_admin import firestore , credentials

cred = credentials.Certificate("AdminSDK.json")
firebase_admin.initialize_app(cred)

db = firestore.client()


def on_snapshot(col_snapshot, changes, read_time):
    print(u'Callback received query snapshot.')
    print(u'Current cities in California: ')
    for change in changes:
        if change.type.name == 'ADDED':
            print(u'New city: {}'.format(change.document.id))
        elif change.type.name == 'MODIFIED':
            print(u'Modified city: {}'.format(change.document.id))
        elif change.type.name == 'REMOVED':
            print(u'Removed city: {}'.format(change.document.id))
col_query = db.collection(u'NeedClassification')
query_watch = col_query.on_snapshot(on_snapshot)

Upvotes: 2

Views: 5024

Answers (1)

ecdemomaniaKay
ecdemomaniaKay

Reputation: 141

I had the same issue and the root cause for me was that I didn't get the script to keep running by adding this at the end:

while True:
time.sleep(1)
print('processing...')

For reference my entire code and output is:

import firebase_admin
import google.cloud
from firebase_admin import credentials, firestore
import time

print('Initializing Firestore connection...')
# Credentials and Firebase App initialization. Always required
firCredentials = credentials.Certificate("./key.json")
firApp = firebase_admin.initialize_app (firCredentials)

# Get access to Firestore
db = firestore.client()
print('Connection initialized')

def on_snapshot(doc_snapshot, changes, read_time):
    for doc in doc_snapshot:
        print(u'Received document snapshot: {}'.format(doc.id))

doc_ref = db.collection('audio').document('filename')
doc_watch = doc_ref.on_snapshot(on_snapshot)

# Keep the app running
while True:
    time.sleep(1)
    print('processing...')

Output (before adding the loop the output stops at Connection initialized):

Initializing Firestore connection...
Connection initialized
Received document snapshot: filename
processing...
processing...
processing...
processing...
processing...
processing...
Received document snapshot: filename
processing...
processing...
# ...[and so on]

Hope this helps.

Upvotes: 14

Related Questions