Check that Firebase app is already initialized in python

I am getting 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 to check if default firebase app is already initialized or not in python?

+5


source to share


6 answers


The best way is to control the application workflow so that initialization is called only once. But of course, inefficient code is good too, so here's what you can do to avoid this error:



import firebase_admin
from firebase_admin import credentials

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

      

+7


source


Initialize application in 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

+3


source


I 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 used it 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')

      

+2


source


I am using this try / block Also to handle application initialization

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

      

+1


source


You can also initialize SDK with no parameters.

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

      

0


source


You can also use the default credentials

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

      

0


source







All Articles