rihekopo
rihekopo

Reputation: 3350

Initializing Firestore-Admin in Flask app

I have a Flask app that uses Cloud Firestore for some functions. I am using the Firestore-Admin library which works fine, but I assume I placed its initializing code wrongly. My knowledge about how Flask apps work is limited so I just simply added the following code to my app.py:

cred = credentials.Certificate('key.json')
fault_app = firebase_admin.initialize_app(cred)
db = firestore.client()

While the code works, my question is that is it a proper solution to initialize the Firestore? Does this solution fits into the lifecycle of a Flask app? I already tried to init the Firestore directly from the methods that use it, but that made server errors because the amount of initializations.

Upvotes: 1

Views: 2439

Answers (2)

Jabbar Memon
Jabbar Memon

Reputation: 83

Below Example Might Help you :

import firebase_admin
from firebase_admin import credentials
from firebase_admin import firestore
from flask import Flask

app = Flask(__name__)

cred = credentials.Certificate("key.json")
firebase_admin.initialize_app(cred)

db = firestore.client()

@app.route('/getdata')
def user_data():

#getting the docs

  users_ref = db.collection('Demo')
  docs = users_ref.get()
  for doc in docs:
      print('{} => {}'.format(doc.id, doc.to_dict()))
  return "Recorded Printed"

if __name__ == '__main__':
app.run()

Upvotes: 1

Hiranya Jayathilaka
Hiranya Jayathilaka

Reputation: 7438

Looks reasonable to me. It's the same approach taken in this tutorial.

Upvotes: 0

Related Questions