Service Account Credentials 是 Firebase 提供的一种服务账户凭证,用于服务器间认证,允许你的应用程序以服务身份而非用户身份访问 Firebase 服务。
from google.oauth2 import service_account
import google.auth.transport.requests
# 正确的凭证加载方式
credentials = service_account.Credentials.from_service_account_file(
'path/to/serviceAccountKey.json',
scopes=['https://www.googleapis.com/auth/firebase.database']
)
# 或者使用字典直接加载
credentials_dict = {
"type": "service_account",
"project_id": "your-project-id",
# 其他必要字段...
}
credentials = service_account.Credentials.from_service_account_info(
credentials_dict,
scopes=['https://www.googleapis.com/auth/firebase.database']
)
检查点:
解决方案:
# 正确设置所需的作用域
SCOPES = [
'https://www.googleapis.com/auth/firebase.database',
'https://www.googleapis.com/auth/userinfo.email',
'https://www.googleapis.com/auth/cloud-platform'
]
credentials = service_account.Credentials.from_service_account_file(
'path/to/serviceAccountKey.json',
scopes=SCOPES
)
import requests
from google.auth.transport.requests import AuthorizedSession
# 创建授权会话
authed_session = AuthorizedSession(credentials)
# 示例:读取 Firebase 实时数据库
response = authed_session.get(
"https://your-project-id.firebaseio.com/path.json"
)
print(response.json())
检查点:
解决方案:
import json
from google.oauth2 import service_account
from google.auth.transport.requests import AuthorizedSession
# 1. 加载服务账户凭证
SERVICE_ACCOUNT_FILE = 'path/to/serviceAccountKey.json'
SCOPES = ['https://www.googleapis.com/auth/firebase.database']
credentials = service_account.Credentials.from_service_account_file(
SERVICE_ACCOUNT_FILE,
scopes=SCOPES
)
# 2. 创建授权会话
authed_session = AuthorizedSession(credentials)
# 3. 定义 Firebase 数据库URL
FIREBASE_URL = "https://your-project-id.firebaseio.com"
# 4. 示例操作
def read_data(path):
url = f"{FIREBASE_URL}/{path}.json"
response = authed_session.get(url)
return response.json()
def write_data(path, data):
url = f"{FIREBASE_URL}/{path}.json"
response = authed_session.put(url, json.dumps(data))
return response.json()
# 使用示例
if __name__ == "__main__":
# 写入数据
write_data("test", {"message": "Hello Firebase"})
# 读取数据
data = read_data("test")
print(data)
如果按照上述步骤仍无法解决问题,建议检查 Firebase 项目日志获取更详细的错误信息。