Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I open a specific database on Google Firestore in Python?

I am using Firebase and setting/retrieving documents from Firestore with this code:

import firebase_admin
from firebase_admin import credentials, firestore

cred = credentials.ApplicationDefault()
firebase_admin.initialize_app(cred, options={"projectId": "huq-jimbo"})
firestore_client = firestore.client()
doc = firestore_client.collection(f"example_collection").document("data")
print(doc)

I can only access the (default) database, and I can't see any way to open a different database.

Looking through the docs (e.g. https://firebase.google.com/docs/firestore/quickstart) it seems there's no database parameter for firestore.client().

How can I achieve this?

like image 966
jimbofreedman Avatar asked Mar 04 '26 22:03

jimbofreedman


2 Answers

According to the reference docs, with 2.17.0 you should now be able to pass in the database name to the instance of the Firebase client you are creating:

firestore.client(database="{database_name}")

You may need to import firestore:

from google.cloud import firestore

If you want to use the Admin SDK, here is another workaround: Accessing Firebase named database from Python SDK

like image 124
jackstruck Avatar answered Mar 07 '26 11:03

jackstruck


based on: firestore.py

Following the suggestion made by the infamous @JonSkeet,

# Only works with `(default)`
db = firestore.client(app)
def getFirestoreClient(app, database):
    from firebase_admin import _utils
    return _utils.get_app_service(app, '_firestore', lambda app: firestore.Client(credentials=app.credential.get_credential(), project=app.project_id, database=database))

# Instead do:
db =  getFirestoreClient(app, 'database_name')
like image 41
darkpbj Avatar answered Mar 07 '26 12:03

darkpbj



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!