Query data from cloud firestore – Python

I have a query that I use to fetch data from cloud firestore .but it throws me a key error. Not sure what is wrong.the code below.

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import pandas as pd
import sys
import os
import fileinput

# Use the application default credentials
cred = credentials.Certificate('creddatabase.json')
firebase_admin.initialize_app(cred)

db = firestore.client()
docs = db.collection(u'testcollection').stream()
users_ref = db.collection(u'testcollection')
docs = users_ref.stream()
array = []
is_header_printed = False

rows_keys = None
out_file = open("testcollection.csv","w")
for doc in docs:
    print(doc.id)
    row_items = doc.to_dict()
    print(doc)
    if(is_header_printed == False):
        rows_keys = list(row_items.keys())
        rows_keys.sort(reverse=False)
        #loop through every key and print the header row
        for key in rows_keys:
            print(key)
            out_file.write(str(key.replace(",","_"))+",")
        out_file.write("n")
        is_header_printed = True
    for key in rows_keys:
        print(key)
        out_file.write(str(row_items[key]).replace(',',' ')+',')
        out_file.write("n")

    print(str(doc.to_dict()['StartDate'].year) + '/' + str(doc.to_dict()['StartDate'].month) + '/' + str(doc.to_dict()['StartDate'].day))
out_file.close()

My document in collection looks like this

Comments: ""
Objectived: "test"
Media: "test media"
notes: "test notest"
Zone A: 0
Zone B: 0

Error message: Traceback (most recent call last):
File "/Users/DataScience/Firebasequery/Firebase_query_for_psolzsol_jnhibtionsingalling.py", line 49, in
out_file.write(str(row_items[key]).replace(‘,’,’ ‘)+’,’)
KeyError: ‘Media’

Source: Python Questions

LEAVE A COMMENT