如何使用 Python 打开 Google Firestore 上的特定数据库?

问题描述 投票:0回答:1

我正在使用 Firebase 并使用以下代码从 Firestore 设置/检索文档:

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)

我只能访问

(default)
数据库,并且看不到任何打开其他数据库的方法。

查看文档(例如https://firebase.google.com/docs/firestore/quickstart),似乎

database
没有
firestore.client()
参数。

我怎样才能实现这个目标?

python firebase google-cloud-platform google-cloud-firestore
1个回答
0
投票

基于:firestore.py

def getFirestoreClient(app, database):
    _FIRESTORE_ATTRIBUTE = '_firestore'
    from firebase_admin import _utils
    
    return _utils.get_app_service(app, _FIRESTORE_ATTRIBUTE, function(app):
        credentials = app.credential.get_credential()
        project = app.project_id
        if not project:
            raise ValueError(
                'Project ID is required to access Firestore. Either set the projectId option, '
                'or use service account credentials. Alternatively, set the GOOGLE_CLOUD_PROJECT '
                'environment variable.')
        return firestore.Client(credentials=credentials, project=project, database=database))
enter code here

按照臭名昭著的@JonSkeet提出的建议,

# only works with `(default)`
db = firestore.client(app)

改为:

db =  getFirestoreClient(app, 'database_name')
© www.soinside.com 2019 - 2024. All rights reserved.