Setup/Acess Firestore on External Server (Python)

April 24, 2019

What is Firestore and why use Firestore

Enable Firestore

Setup Firestore on External Server (Python)

Depedencies

pip install flask
pip install firebase-admin
from flask import Flask, jsonify, abort

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore

app = 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 jsonify
from google.cloud import firestore

db = 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:

This work is licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License.