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'

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...