'check if a Firebase App is already initialized in python

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?



Solution 1:[1]

The best way is to control your app workflow so the initialization is called only once. But of course, idempotent code is also a good thing, so here is what you can do to avoid that error:

import firebase_admin
from firebase_admin import credentials

if not firebase_admin._apps:
    cred = credentials.Certificate('path/to/serviceAccountKey.json') 
    default_app = firebase_admin.initialize_app(cred)

Solution 2:[2]

Initialize the app in the constructor

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

then in your method you call

firebase_admin.get_app()

https://firebase.google.com/docs/reference/admin/python/firebase_admin

Solution 3:[3]

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)

Solution 4:[4]

I've found the following to work for me.

For the default app:

import firebase_admin
from firebase_admin import credentials

if firebase_admin._DEFAULT_APP_NAME in firebase_admin._apps:
    # do something.

I have been using it in this way with a named app:

import firebase_admin
from firebase_admin import credentials

if 'my_app_name' not in firebase_admin._apps:
    cred = credentials.Certificate('path/to/serviceAccountKey.json')        
    firebase_admin.initialize_app(cred, {
            'databaseURL': 'https://{}.firebaseio.com'.format(project_id),
            'storageBucket': '{}.appspot.com'.format(project_id)}, name='my_app_name')

Solution 5:[5]

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()

Solution 6:[6]

You can also use default credentials

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

Solution 7:[7]

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!!

Solution 8:[8]

You can use

firebase_admin.delete_app(firebase_admin.get_app())

And execute the code again

Solution 9:[9]

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

Solution 10:[10]

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"""