check if a Firebase App is already initialized in python

Viewed 25600

I get the following error:

ValueError: The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name.

How Can I check if the default firebase app is already initialized or not in python?

11 Answers

I use this try / except block to handle initialisation of the app

try:
    app = firebase_admin.get_app()
except ValueError as e:
    cred = credentials.Certificate(CREDENTIALS_FIREBASE_PATH)
    firebase_admin.initialize_app(cred)

If you ended up here due to building Cloud Functions in GCP with Python that interacts with Firestore, then this is what worked for me:

The reason for using an exception for control flow here is that the firebase_admin._apps is a protected member of the module, so accessing it directly is not best practice either.

import firebase_admin
from firebase_admin import credentials, firestore


def init_with_service_account(file_path):
     """
     Initialize the Firestore DB client using a service account
     :param file_path: path to service account
     :return: firestore
     """
     cred = credentials.Certificate(file_path)
     try:
         firebase_admin.get_app()
     except ValueError:
         firebase_admin.initialize_app(cred)
     return firestore.client()


def init_with_project_id(project_id):
    """
    Initialize the Firestore DB client using a GCP project ID
    :param project_id: The GCP project ID
    :return: firestore
    """
    cred = credentials.ApplicationDefault()
    try:
        firebase_admin.get_app()
    except ValueError:
        firebase_admin.initialize_app(cred)
    return firestore.client()

You can also use default credentials

 if (not len(firebase_admin._apps)):
    cred = credentials.ApplicationDefault()
    firebase_admin.initialize_app(cred, {
        'projectId': "yourprojetid"})

In my case, I faced a similar error. But my issue was, I have initialized the app twice in my python file. So it crashed my whole python file and returns a
ValueError: The default Firebase app already exists. This means you called initialize_app() more than once without providing an app name as the second argument. In most cases you only need to call initialize_app() once. But if you do want to initialize multiple apps, pass a second argument to initialize_app() to give each app a unique name. I solved this by removing one of my firebase app initialization. I hope this will help someone!!

You can use

firebase_admin.delete_app(firebase_admin.get_app())

And execute the code again

Reinitializing more than one app in firebase using python:

You need to give different name for different app

For every app we will be generating one object store those objects in list and access those object one by one later

def getprojectid(proj_url):
    p = r'//(.*)\.firebaseio'
    x = re.findall(p, url)
    return x[0]

objects = []
count = 0
details = dict()

def addtofirebase(json_path, url):
    global objects, count, details
    my_app_name = getprojectid(url) # Function which returns project ID
    if my_app_name not in firebase_admin._apps: 
            cred = credentials.Certificate(json_path)        
            obj = firebase_admin.initialize_app(cred,xyz , name=my_app_name) # create the object
            objects.append(obj) # Store Initialized Objects in one list
            details[my_app_name] = count # Storing index of object in dictionary to access it later using project id 
            count += 1
            ref = db.reference('/',app= objects[details[my_app_name])  # using this reference, change database

        else:
            ref = db.reference('/',app= objects[details[my_app_name])  # from next time it will get update here. it will not get initialise again and again

Make the the app global, don't put the initialize_app() inside the function because whenever the function called it also calls the initialize_app() again.

CRED = credentials.Certificate('path/to/serviceAccountKey.json') 
DEFAULT_APP = firebase_admin.initialize_app(cred)

def function():
    """call default_app and process data here"""

Use don't need key.json file. You can default gcloud credentials to authenticate.

gcloud auth application-default login --project="yourproject"

python code: import firebase_admin

app_options = {'projectId': 'yourproject'}
default_app = firebase_admin.initialize_app(options=app_options)
Related