Python Firestore Asyncio

December 9, 2020

Environment

Ubuntu 20.04.1 LTS
Python 3.8.6 
firebase-admin==4.4.0
google-cloud-core==1.4.3
google-cloud-firestore==2.0.1
grpcio==1.33.2

NOTE: asyncio seems to be supported since google-cloud-firestore==2.0.0

Usage

import asyncio
import sys
import firebase_admin
from firebase_admin import credentials, firestore, auth
from firebase_admin.firestore import AsyncDocumentReference
# from firebase_admin.firestore import AsyncClient

async def main():
    cred = credentials.Certificate('firebase-adminsdk.json')
    app = firebase_admin.initialize_app(cred)
    # db = firestore.client(app = app)
    db = firestore.AsyncClient(credentials=app.credential.get_credential(), project=app.project_id)
    user_ref = db.collection('user')

    ref = user_ref.document()
    await ref.set({'name': 'test-user'})

    docs = await user_ref.get()
    for doc in docs:
        print(doc.id, doc.get('name'))


    docs = user_ref.stream()
    async for doc in docs:
        print(doc.id, doc.get('name'))

    print('END')


if __name__ == "__main__":
    asyncio.run(main())
    print('main-END')

References:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.