Skip to content

Instantly share code, notes, and snippets.

@gh640
Last active Dec 13, 2021
Embed
What would you like to do?
Sample: Script to export Firestore collection as CSV
"""Script to export Firestore collection as CSV."""
import csv
import sys
from pathlib import Path
from firebase_admin import credentials, firestore, initialize_app
CRED_FILE = Path(__name__).resolve().parent / 'firebase-privateKey.json'
COLLECTION_NAME = 'XXX'
FIELDS = ['name', 'body', 'created']
DIRECTION = firestore.Query.DESCENDING
def main():
"""Main function"""
client = firebase_client(str(CRED_FILE))
collection = client.collection(COLLECTION_NAME)
writer = csv_writer(sys.stdout, FIELDS)
writer.writeheader()
for snapshot in collection.order_by('created', direction=DIRECTION).get():
data = snapshot.to_dict()
writer.writerow(data)
def firebase_client(cred_file):
"""Generate Firebase client"""
cred = credentials.Certificate(cred_file)
app = initialize_app(credential=cred)
client = firestore.client(app=app)
return client
def csv_writer(file, fields):
"""Generate CSV writer"""
return csv.DictWriter(file, fields)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment