Setup/Acess Firestore on External Server (Python)

Apr 24, 2019

What is Firestore and why use Firestore

Enable 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:

❤️ Is this article helpful?

Buy me a coffee ☕ or support my work via PayPal to keep this space 🖖 and ad-free.

Do send some 💖 to @d_luaz or share this article.

✨ By Desmond Lua

A dream boy who enjoys making apps, travelling and making youtube videos. Follow me on @d_luaz

👶 Apps I built

Travelopy - discover travel places in Malaysia, Singapore, Taiwan, Japan.