python

Check if firebase app is initialized in Python

If you are using firebase admin in your python project and getting the error - The default Firebase app already exists. Then you can use the code examples explained here.

import firebase_admin
from firebase_admin import credentials, firestore

if not firebase_admin._apps:
    cred = credentials.Certificate('key_file_path.json')
    firebase_admin.initialize_app(cred)

The error may look like as below:

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.

We are using if not firebase_admin._apps: to check if the app is initialized or not.


Initialize firebase app in Django view

If you are using Django in your project and initiating the app in the view then you can also use the below code.

import pathlib
import firebase_admin
from firebase_admin import credentials, firestore
from django.shortcuts import render

def index(request):
    path = pathlib.Path().resolve()
    gkey_file_path = str(path) + "/keys/" + "key_file_name.json"

    if not firebase_admin._apps:
        cred = credentials.Certificate(gkey_file_path)
        firebase_admin.initialize_app(cred)

    db = firestore.client()

    feed_ref = db.collection(u'collection_name')
    query = feed_ref.order_by(u'name', direction=firestore.Query.DESCENDING).limit(15)
    docs = query.stream()

    feeds = []
    for doc in docs:
        feeds.append(doc.to_dict())

    context = {
        "feeds": feeds
    }

    return render(request, 'feeds/feed.html', context)

Initialize using try/except

You can also use try/except if the app is not initialized:

import firebase_admin
from firebase_admin import credentials, firestore

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

This is an example of initializing the Firebase Admin SDK with a service account. First, it tries to get an existing app. If there is no existing app, it creates a new app with a service account.


Was this helpful?