What is Firestore and why use Firestore
Setup Google Cloud Functions Using Python
via firebase_admin
Add firebase-admin
to requirements.txt
.
# https://pypi.org/project/firebase-admin/
firebase-admin==2.16.0
Code
from flask import jsonify, abortimport firebase_adminfrom firebase_admin import credentialsfrom firebase_admin import firestorePROJECT_ID = ...cred = credentials.ApplicationDefault()default_app = firebase_admin.initialize_app(cred, { 'projectId': PROJECT_ID,})db = firestore.client()def test_firestore(request): doc_ref = db.collection('COLLECTION').document('DOCUMENT_ID') doc = doc_ref.get() if doc.exists: return jsonify(doc.to_dict()) else: doc_ref.set({'name': 'Hello'}) return 'UPDATED'
NOTE: TypeError
exception is raised by jsonify
when some data is not JSON serializable (e.g. DocumentReference
)
via google-cloud-firestore
Add google-cloud-firestore
to requirements.txt
.
# https://pypi.org/project/google-cloud-firestore/
google-cloud-firestore==1.3.0
Code
from flask import jsonifyfrom google.cloud import firestore# db = firestore.Client.from_service_account_json('PROJECT_ID-firestore.json')db = firestore.Client()def test_firestore(request): doc_ref = db.collection('test').document('xxx') doc = doc_ref.get() if doc.exists: return jsonify(doc.to_dict()) else: doc_ref.set({'name': 'Hello'}) return 'UPDATED'
Deploy
References: