Google Cloud Datastore NDB 客户端库指南
项目介绍
Google Cloud Datastore NDB 客户端库 是一个专为在 Google App Engine 的 Python 运行环境中与 Google Cloud Datastore 交互而设计的客户端库。它提供了一套高级数据模型抽象,使得开发者能够更简便地管理和操作云数据。尽管这个库原本是面向Python 2且仅限于App Engine环境,但请注意,对于支持Python 3并兼容非App Engine环境的需求,应转向更新的版本或查看 googleapis/python-ndb。
项目快速启动
在开始之前,确保你已经安装了Google Cloud SDK,并配置好了你的Google Cloud项目。
步骤一:安装库
由于原始仓库已归档,对新项目推荐使用最新版本的ndb库。以下是安装更新后的版本(python-ndb)的方法:
pip install google-cloud-ndb
步骤二:初始化示例
以下是如何创建一个简单的数据模型并在Google Cloud Datastore中存储数据的例子。
首先,导入必要的库并定义数据模型:
from google.cloud import ndb
class User(ndb.Model):
name = ndb.StringProperty()
email = ndb.StringProperty()
# 初始化客户端,通常这一步会在应用的入口处完成
client = ndb.Client()
with client.context():
# 创建一个新的用户实体
new_user = User(name='Alice', email='alice@example.com')
new_user.put() # 将实体保存到Datastore
# 查询用户
key = ndb.Key(User, 'alice-key') # 假设我们知道用户的键
alice = key.get()
print(f"User's name: {alice.name}, Email: {alice.email}")
应用案例和最佳实践
在实际应用中,NDB的高级特性和异步查询能力特别有用。例如,利用其上下文管理器进行事务处理可以保证数据的一致性:
def transfer_funds(sender_key, receiver_key, amount):
with client.transaction():
sender = sender_key.get()
receiver = receiver_key.get()
if sender.balance >= amount:
sender.balance -= amount
receiver.balance += amount
sender.put()
receiver.put()
else:
raise ValueError("Insufficient funds.")
最佳实践中,确保合理组织实体关系,使用缓存策略减少不必要的API调用,并始终关注查询效率,避免全量查询。
典型生态项目
虽然本指引主要集中在datastore-ndb-python项目上,但在现代实践中,开发基于Google Cloud的Python应用时,结合使用google-cloud-ndb和其他Google Cloud Python客户端库是常见的做法。这些生态项目包括但不限于google-cloud-storage、google-cloud-firestore等,它们共同支撑起复杂应用的后端服务。对于构建扩展性强、跨多个Google Cloud服务的应用,理解这些库如何协同工作是非常重要的。
请注意,对于最新的功能和最佳实践,建议参考Google Cloud的官方文档和最新的python-ndb库,以获得对Python 3的支持及适应更广泛的部署场景。
atomcodeClaude Code 的开源替代方案。连接任意大模型,编辑代码,运行命令,自动验证 — 全自动执行。用 Rust 构建,极致性能。 | An open-source alternative to Claude Code. Connect any LLM, edit code, run commands, and verify changes — autonomously. Built in Rust for speed. Get StartedRust0215
cann-learning-hubCANN 学习中心仓,支持在线互动运行、边学边练,提供教程、示例与优化方案,一站式助力昇腾开发者快速上手。Jupyter Notebook0138
uni-appA cross-platform framework using Vue.jsJavaScript08
GLM-5.2智谱开源 GLM-5.2,这是针对长文本任务的最新旗舰模型。相较于前代产品 GLM-5.1,它在长文本任务处理能力上实现了显著飞跃,并且首次在稳定的 100 万 token 上下文中提供这一能力。Jinja00
SwanLab⚡️SwanLab - an open-source, modern-design AI training tracking and visualization tool. Supports Cloud / Self-hosted use. Integrated with PyTorch / Transformers / LLaMA Factory / veRL/ Swift / Ultralytics / MMEngine / Keras etc.Python00
tiny-universe《大模型白盒子构建指南》:一个全手搓的Tiny-UniverseJupyter Notebook03