Skip to content

Instantly share code, notes, and snippets.

@gh640
Last active January 29, 2023 18:14
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gh640/eeaf9f24bce067e57e39a8defdafa480 to your computer and use it in GitHub Desktop.
Save gh640/eeaf9f24bce067e57e39a8defdafa480 to your computer and use it in GitHub Desktop.
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(__file__).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