Home > database >  Deleting a Firestore collection with async/await in Python
Deleting a Firestore collection with async/await in Python

Time:11-15

I'm using Firebase Admin SDK with python and would like to delete a Firestore collection with Async/Await clause.

The official document says that (non-Async/Await) deleting should be done like this:

def delete_collection(col_ref, batch_size):
    docs = col_ref.limit(batch_size).stream()
    deleted = 0

    for doc in docs:
        print(f'Deleting doc {doc.id} => {doc.to_dict()}')
        doc.reference.delete()
        deleted = deleted   1


    if deleted >= batch_size:
        return delete_collection(col_ref, batch_size)

But, this does not work well in Async/Await version. If I put AsyncCollectionReference in the col_ref, it will cause this error:

TypeError: 'async_generator' object is not iterable

Is it possible to fix this probem? Or, is it an totally wrong idea to do Async/Await batch delete?

Thanks!

CodePudding user response:

Try adding async/await statements to your code:

async def delete_collection(coll_ref, batch_size):
    docs = coll_ref.limit(batch_size).stream()
    deleted = 0

    async for doc in docs:
        print(f"Deleting doc {doc.id} => {doc.to_dict()}")
        await doc.reference.delete()
        deleted = deleted   1

    if deleted >= batch_size:
        return delete_collection(coll_ref, batch_size)
  • Related