我正在使用 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()
参数。
我怎样才能实现这个目标?
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')