/firestore_backup

Primary LanguagePythonMIT LicenseMIT

Firestore Backup Script - using Firebase Admin Python SDK

Installation

First install and setup Firebase Admin Python SDK: https://firebase.google.com/docs/admin/setup

Then install it in your python environment:

pip install firebase-admin

Then install PyMongo in your python environment:

pip install pymongo

Backup script

# -*- coding: UTF-8 -*-

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import json
from bson import json_util

'''
The serviceAccountKey.json file must be generated by firebase 
in the dashboard, settings, service account.
'''
cred = credentials.Certificate('serviceAccountKey.json')  # from firebase project settings
firebase_admin.initialize_app(cred)
firestore_client = firestore.client()


def import_collections(reference) -> dict:
		dict4json = dict()
		collections = reference.collections()

		for collectionRef in collections:
				dict4json[collectionRef.id] = {}
				for documentRef in collectionRef.list_documents():
						dict4json[collectionRef.id][documentRef.id] = {}

						dict4json[collectionRef.id][documentRef.id]['documentData'] = documentRef.get(
						).to_dict()
						dict4json[collectionRef.id][documentRef.id]['documentSubcollections'] = import_collections(
								documentRef)
		return dict4json


dict4json = import_collections(firestore_client)
print(dict4json)

jsonfromdict = json.dumps(dict4json, indent=4, default=json_util.default)

with open('firestore_backup.json', 'w') as the_file:
		the_file.write(jsonfromdict)

input('Press [enter] to exit...')

Upload script

# -*- coding: UTF-8 -*-

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
import json
from bson import json_util

'''
The serviceAccountKey.json file must be generated by firebase 
in the dashboard, settings, service account.
'''
cred = credentials.Certificate('serviceAccountKey.json')
firebase_admin.initialize_app(cred)
firestore_client = firestore.client()

with open('firestore_backup.json') as json_file:
		json_data = json.load(json_file, object_hook=json_util.object_hook, )


def upload_database(data: dict, reference):
		for collectionName, documents in data.items():
				for documentId, documentContent in documents.items():
						documentData = documentContent['documentData']
						documentSubcollections = documentContent['documentSubcollections']
						documentReference = reference.collection(
								collectionName).document(documentId)
						# you may change it to [merge] False if you want to
						documentReference.set(documentData, merge=True)
						upload_database(data=documentSubcollections,
														reference=documentReference)


upload_database(data=json_data, reference=firestore_client)

input('Press [enter] to exit...')

Documentation Reference

https://firebase.google.com/docs/reference/admin/python/firebase_admin.firestore