Last active
May 30, 2024 08:00
-
-
Save gh640/eeaf9f24bce067e57e39a8defdafa480 to your computer and use it in GitHub Desktop.
Sample: Script to export Firestore collection as CSV
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
"""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