# To run code use: python upload-json-file-to-firestore.py data.json add users-demo-add# for command line arguements.importsysimportjson# SETTING UP YOUR VIRTUAL ENVIRONMENT# For Mac# pip install virtualenv# virtualenv <your-env># source tutoring/bin/activate# tutoring/bin/pip install google-cloud-firestore# For Window# pip install virtualenv# virtualenv <your-env># <your-env>\Scripts\activate# <your-env>\Scripts\pip.exe install google-cloud-firestoreimportfirebase_adminfromfirebase_adminimportcredentialsfromfirebase_adminimportfirestoreimporttimeit# Use a service accountcred=credentials.Certificate('service-account.json')firebase_admin.initialize_app(cred)db=firestore.client()classUploadJsonFileToFirestore:def__init__(self)->None:# Get class running timeself.start=timeit.default_timer()# Check to make sure the command line arguements # are atleast 3 arguementsiflen(sys.argv[1:])!=3:print(f'ERROR: Check your command line arguments!,\n 3 arguements expected [file=filepath, method=[set or add], collectionname=[firestore collection name]')returnNone# Initialize instance variablesself.json_data=sys.argv[1:][0]self.method=sys.argv[1:][1]self.collectionname=sys.argv[1:][2]def__str__(self)->str:return(f'Uploading ****{self.file}***** JSON items to firestore!')# Firestore upload method getter method@propertydefmethod(self):returnself._method# Firestore upload method setter method@method.setterdefmethod(self,val):ifval=='set'orval=='add':self._method=valelse:print(f'Wrong method {val}, use set or add')# Get Json file path property@propertydefjson_data(self):returnself._json_data# Set and process Json file path property@json_data.setterdefjson_data(self,val):ifval:try:# Opening JSON filef=open(val,)# returns JSON object as a dictionarydata=json.load(f)# make sure to close filef.close()self._json_data=dataexceptExceptionase:print(f'FILE EXCEPTION: {str(e)}')else:print(f'Wrong file path {val}')# Main class method to populate firestore # With the said datadefupload(self):ifself.json_dataandself.method:# Iterating through the json listforidx,iteminenumerate(self.json_data):''' START FOR JUST FOR DEMO REASONS '''frompygmentsimporthighlightfrompygments.lexersimportJsonLexerfrompygments.formattersimportTerminalFormatterjson_str=json.dumps(item,indent=4,sort_keys=True)print(highlight(json_str,JsonLexer(),TerminalFormatter()))''' END FOR JUST FOR DEMO REASONS '''ifself.method=='set':self.set(item)else:self.add(item)# Successfully got to end of data;# print success messageifidx==len(self.json_data)-1:# All the program statementsstop=timeit.default_timer()print('**************************\n****SUCCESS UPLOAD*****\n**************************')print("Time taken "+str(stop-self.start))# Collection Add method# Adds all data under a collection# With firebase firestore auto generated IDSdefadd(self,item):returndb.collection(self.collectionname).add(item)# Collection document set method# Adds all data under a collection# With custom document IDS defset(self,item):returndb.collection(self.collectionname).document(str(item['id'])).set(item)uploadjson=UploadJsonFileToFirestore()uploadjson.upload()