Python Firebase Admin SDK - DefaultCredentialsError

Python Firebase Admin SDK - DefaultCredentialsError

我在为 Python 初始化 Firebase Admin SDK 时设置凭据时遇到问题。从 here 中汲取灵感,我将其设置为:

import firebase_admin
from firebase_admin import credentials, firestore

cred = credentials.Certificate('./serviceAccountKey.json')
firebase_admin.initialize_app(cred)
db = firestore.Client()

...但这会导致:

raise exceptions.DefaultCredentialsError(_HELP_MESSAGE)
google.auth.exceptions.DefaultCredentialsError: Could not automatically determine credentials. Please set GOOGLE_APPLICATION_CREDENTIALS or explicitly create credentials and re-run the application.

我能让它工作的唯一方法是先创建一个像这样的 GOOGLE_APPLICATION_CREDENTIALS 环境变量:

export GOOGLE_APPLICATION_CREDENTIALS="serviceAccountKey.json"

对于credentials.Certificate(path)的路径,我试过'./serviceAccountKey.json''serviceAccountKey.json',甚至是绝对路径,'/home/pi/projects/serviceAccountKey.json'

我正在 Raspberry Pi.

中执行此操作

如何在无需显式设置 GOOGLE_APPLICATION_CREDENTIALS 环境变量的情况下使凭据起作用?

您可以使用 environ

在本地设置环境变量
import os
>>> os.environ["GOOGLE_APPLICATION_CREDENTIALS"]
    './serviceAccountKey.json'

import os
os.environ['GOOGLE_APPLICATION_CREDENTIALS'] = './serviceAccountKey.json'