HappyBase API hello world
本示例是一个非常简单的“hello world”应用,采用 Python 编写而成,旨在说明如何实现以下操作:
- 设置身份验证
- 连接到 Bigtable 实例。
- 新建一个表。
- 将数据写入表中。
- 重新读取这些数据。
- 删除表。
设置身份验证
如需在本地开发环境中使用本页面上的 Python 示例,请安装并初始化 gcloud CLI,然后使用您的用户凭证设置应用默认凭证。
-
Install the Google Cloud CLI.
-
If you're using an external identity provider (IdP), you must first sign in to the gcloud CLI with your federated identity.
-
To initialize the gcloud CLI, run the following command:
gcloud init
-
If you're using a local shell, then create local authentication credentials for your user account:
gcloud auth application-default login
You don't need to do this if you're using Cloud Shell.
If an authentication error is returned, and you are using an external identity provider (IdP), confirm that you have signed in to the gcloud CLI with your federated identity.
如需了解详情,请参阅 Set up authentication for a local development environment。 如需了解详情,请参阅身份验证文档中的为本地开发环境设置 ADC。
运行示例
本示例使用 Python 版 Google Cloud 客户端库的 HappyBase 软件包(HappyBase API 的一种实现)与 Bigtable 通信。如果您需要将现有 HBase 工作负载移至 Bigtable,请使用 HappyBase 软件包。对于新应用,请参阅使用 Bigtable 软件包的“hello world”示例。
要运行此示例程序,请按照 GitHub 上的示例说明执行操作。
将 HappyBase API 与 Bigtable 搭配使用
示例应用会连接到 Bigtable 并演示一些简单操作。
安装和导入客户端库
您可以使用 PIP 将所需的 Python 软件包安装到 virtualenv 环境中。该示例包含一个需求文件,其中定义了所需的软件包。
然后可以导入模块。
连接到 Bigtable
将 bigtable.Client
传递到 happybase.Connection
即可连接到 Bigtable。
创建表
使用 Connection.create_table()
创建表及其列族。
将行写入表
使用 Connection.table()
获取现有 Table
。然后使用 Table.put()
向该表中写入一行。
按行键读取行
通过 Table.row()
使用行键直接获取行。
扫描所有表行
使用 Table.scan()
获取一定范围的行。
删除表
使用 Connection.delete_table()
删除表。
综合应用
以下为不包含注释的完整示例。