What is Firestore and why use Firestore
Setup Firestore on External Server (Python)
Depedencies
pip install flaskpip install firebase-admin
from flask import Flask, jsonify, abortimport firebase_adminfrom firebase_admin import credentialsfrom firebase_admin import firestoreapp = Flask(__name__)cred = credentials.Certificate('keys/firebase-adminsdk.json')default_app = firebase_admin.initialize_app(cred, { 'projectId': 'nuanxindan',})db = firestore.client()@app.route('/test_firestore')def test_firestore(): 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: Goto Google Cloud Console -> Service Accounts, find firebase-adminsdk
and click Create key
and download the json file as firebase-adminsdk.json
.
via google-cloud-firestore
Depedencies
pip install google-cloud-firestore
Code
from flask import jsonifyfrom google.cloud import firestoredb = firestore.Client.from_service_account_json('PROJECT_ID-firestore.json')# db = firestore.Client()@app.route('/test_firestore')def test_firestore(): 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'
References: