在 App Engine 项目中添加适当的服务账户,并授权其访问 Firestore。以下代码示例展示了如何在 Python 中使用 Google Auth 库指定服务账户:
from google.auth import compute_engine
from google.cloud import firestore
# 如果在 Google Compute Engine 中部署,则使用默认凭据
if compute_engine.is_running_vm():
client = firestore.Client()
else:
# 否则,明确指定服务账户凭据文件路径
cred = credentials.Certificate('/path/to/service-account-key.json')
client = firestore.Client(credentials=cred)
# 使用 Firestore 客户端进行 CRUD 操作
请注意,/path/to/service-account-key.json
是你自己的服务账户密钥文件路径。你可以在 Google Cloud Console 的“IAM & Admin”>“Service Accounts”页面上创建服务账户并生成此文件。另外,请确保你已启用了 Google Cloud Firestore API。