Skip to content

Commit f228cc6

Browse files
committed
Add Bigtable hello world sample.
1 parent f67e7c2 commit f228cc6

File tree

9 files changed

+230
-4
lines changed

9 files changed

+230
-4
lines changed

.coveragerc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
[run]
22
include =
33
appengine/*
4+
bigtable/*
45
bigquery/*
56
blog/*
67
cloud_logging/*

bigtable/hello/README.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Cloud Bigtable Hello World
2+
3+
This is a simple application that demonstrates using the [Google Cloud Client
4+
Library][gcloud-python] to connect to and interact with Cloud Bigtable.
5+
6+
[gcloud-python]: https://github.com/GoogleCloudPlatform/gcloud-python
7+
8+
9+
## Provision a cluster
10+
11+
Follow the instructions in the [user documentation](https://cloud.google.com/bigtable/docs/creating-cluster)
12+
to create a Google Cloud Platform project and Cloud Bigtable cluster if necessary.
13+
You'll need to reference your project ID, zone and cluster ID to run the application.
14+
15+
16+
## Run the application
17+
18+
First, set your [Google Application Default Credentials](https://developers.google.com/identity/protocols/application-default-credentials)
19+
20+
Install the dependencies with pip.
21+
22+
```
23+
$ pip install -r requirements.txt
24+
```
25+
26+
Run the application. Replace the command-line parameters with values for your cluster.
27+
28+
```
29+
$ python main.py my-project my-cluster us-central1-c
30+
```
31+
32+
You will see output resembling the following:
33+
34+
```
35+
Create table Hello-Bigtable-1234
36+
Write some greetings to the table
37+
Scan for all greetings:
38+
greeting0: Hello World!
39+
greeting1: Hello Cloud Bigtable!
40+
greeting2: Hello HappyBase!
41+
Delete table Hello-Bigtable-1234
42+
```
43+
44+
## Understanding the code
45+
46+
The [application](main.py) uses the [Google Cloud Bigtable HappyBase
47+
package][Bigtable HappyBase], an implementation of the [HappyBase][HappyBase]
48+
library, to make calls to Cloud Bigtable. It demonstrates several basic
49+
concepts of working with Cloud Bigtable via this API:
50+
51+
[Bigtable HappyBase]: https://googlecloudplatform.github.io/gcloud-python/stable/happybase-package.html
52+
[HappyBase]: http://happybase.readthedocs.io/en/latest/index.html
53+
54+
- Creating a [Connection][HappyBase Connection] to a Cloud Bigtable
55+
[Cluster][Cluster API].
56+
- Using the [Connection][HappyBase Connection] interface to create, disable and
57+
delete a [Table][HappyBase Table].
58+
- Using the Connection to get a Table.
59+
- Using the Table to write rows via a [put][HappyBase Table Put] and scan
60+
across multiple rows using [scan][HappyBase Table Scan].
61+
62+
[Cluster API]: https://googlecloudplatform.github.io/gcloud-python/stable/bigtable-cluster.html
63+
[HappyBase Connection]: https://googlecloudplatform.github.io/gcloud-python/stable/happybase-connection.html
64+
[HappyBase Table]: https://googlecloudplatform.github.io/gcloud-python/stable/happybase-table.html
65+
[HappyBase Table Put]: https://googlecloudplatform.github.io/gcloud-python/stable/happybase-table.html#gcloud.bigtable.happybase.table.Table.put
66+
[HappyBase Table Scan]: https://googlecloudplatform.github.io/gcloud-python/stable/happybase-table.html#gcloud.bigtable.happybase.table.Table.scan
67+

bigtable/hello/main.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
#!/usr/bin/env python
2+
3+
# Copyright 2016 Google Inc.
4+
#
5+
# Licensed under the Apache License, Version 2.0 (the "License");
6+
# you may not use this file except in compliance with the License.
7+
# You may obtain a copy of the License at
8+
#
9+
# http://www.apache.org/licenses/LICENSE-2.0
10+
#
11+
# Unless required by applicable law or agreed to in writing, software
12+
# distributed under the License is distributed on an "AS IS" BASIS,
13+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14+
# See the License for the specific language governing permissions and
15+
# limitations under the License.
16+
17+
"""Demonstrates how to connect to Cloud Bigtable and run some basic operations.
18+
19+
Prerequisites:
20+
21+
- Create a Cloud Bigtable cluster.
22+
https://cloud.google.com/bigtable/docs/creating-cluster
23+
- Set your Google Application Default Credentials.
24+
https://developers.google.com/identity/protocols/application-default-credentials
25+
- Set the GCLOUD_PROJECT environment variable to your project ID.
26+
https://support.google.com/cloud/answer/6158840
27+
"""
28+
29+
import argparse
30+
import uuid
31+
32+
from gcloud import bigtable
33+
from gcloud.bigtable import happybase
34+
35+
36+
def main(project, cluster_id, zone, table_name):
37+
# The client must be created with admin=True because it will create a
38+
# table.
39+
client = bigtable.Client(project=project, admin=True)
40+
41+
with client:
42+
cluster = client.cluster(zone, cluster_id)
43+
cluster.reload()
44+
connection = happybase.Connection(cluster=cluster)
45+
46+
print('Creating the {} table.'.format(table_name))
47+
column_family_name = 'cf1'
48+
connection.create_table(
49+
table_name,
50+
{
51+
column_family_name: dict() # Use default options.
52+
})
53+
table = connection.table(table_name)
54+
55+
print('Writing some greetings to the table.')
56+
column_name = '{fam}:greeting'.format(fam=column_family_name)
57+
greetings = [
58+
'Hello World!',
59+
'Hello Cloud Bigtable!',
60+
'Hello HappyBase!',
61+
]
62+
for value in greetings:
63+
# Use a random key to distribute writes more evenly across shards.
64+
# See: https://cloud.google.com/bigtable/docs/schema-design
65+
row_key = str(uuid.uuid4())
66+
table.put(row_key, {column_name: value})
67+
68+
print('Scanning for all greetings:')
69+
for key, row in table.scan():
70+
print('\t{}: {}'.format(key, row[column_name]))
71+
72+
print('Deleting the {} table.'.format(table_name))
73+
connection.delete_table(table_name)
74+
75+
76+
if __name__ == '__main__':
77+
parser = argparse.ArgumentParser(
78+
description='A sample application that connects to Cloud' +
79+
' Bigtable.',
80+
formatter_class=argparse.ArgumentDefaultsHelpFormatter)
81+
parser.add_argument(
82+
'project',
83+
help='Google Cloud Platform project ID that contains the Cloud' +
84+
' Bigtable cluster.')
85+
parser.add_argument(
86+
'cluster', help='ID of the Cloud Bigtable cluster to connect to.')
87+
parser.add_argument(
88+
'zone', help='Zone that contains the Cloud Bigtable cluster.')
89+
parser.add_argument(
90+
'--table',
91+
help='Table to create and destroy.',
92+
default='Hello-Bigtable')
93+
94+
args = parser.parse_args()
95+
main(args.project, args.cluster, args.zone, args.table)

bigtable/hello/main_test.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
# Copyright 2016 Google Inc.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License");
4+
# you may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
import random
16+
import re
17+
import sys
18+
19+
from hello import main
20+
21+
import pytest
22+
23+
TABLE_NAME_FORMAT = 'Hello-Bigtable-{}'
24+
TABLE_NAME_RANGE = 10000
25+
26+
27+
@pytest.mark.skipif(
28+
sys.version_info >= (3, 0),
29+
reason=("grpc doesn't yet support python3 "
30+
'https://github.com/grpc/grpc/issues/282'))
31+
def test_main(cloud_config, capsys):
32+
table_name = TABLE_NAME_FORMAT.format(
33+
random.randrange(TABLE_NAME_RANGE))
34+
main(
35+
cloud_config.project,
36+
cloud_config.bigtable_cluster,
37+
cloud_config.bigtable_zone,
38+
table_name)
39+
40+
out, _ = capsys.readouterr()
41+
assert re.search(
42+
re.compile(r'Creating the Hello-Bigtable-[0-9]+ table\.'), out)
43+
assert re.search(re.compile(r'Writing some greetings to the table\.'), out)
44+
assert re.search(re.compile(r'Scanning for all greetings'), out)
45+
assert re.search(re.compile(r'greeting0: Hello World!'), out)
46+
assert re.search(
47+
re.compile(r'Deleting the Hello-Bigtable-[0-9]+ table\.'), out)

bigtable/hello/requirements.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
gcloud[grpc]==0.14.0

conftest.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,9 @@ def cloud_config():
2828
return Namespace(
2929
project=os.environ.get('GCLOUD_PROJECT'),
3030
storage_bucket=os.environ.get('CLOUD_STORAGE_BUCKET'),
31-
client_secrets=os.environ.get('GOOGLE_CLIENT_SECRETS'))
31+
client_secrets=os.environ.get('GOOGLE_CLIENT_SECRETS'),
32+
bigtable_cluster=os.environ.get('BIGTABLE_CLUSTER'),
33+
bigtable_zone=os.environ.get('BIGTABLE_ZONE'))
3234

3335

3436
def get_resource_path(resource, local_path):

nox.py

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -26,8 +26,13 @@
2626
'-x', '--no-success-flaky-report', '--cov', '--cov-config',
2727
'.coveragerc', '--cov-append', '--cov-report=']
2828

29-
# Speech is temporarily disabled.
30-
TESTS_BLACKLIST = set(('./appengine/standard', './testing', './speech'))
29+
# Bigtable and Speech are disabled because they use gRPC, which does not yet
30+
# support Python 3. See: https://github.com/grpc/grpc/issues/282
31+
TESTS_BLACKLIST = set((
32+
'./appengine/standard',
33+
'./bigtable',
34+
'./speech',
35+
'./testing'))
3136
APPENGINE_BLACKLIST = set()
3237

3338

scripts/prepare-testing-project.sh

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ echo "Creating cloud storage bucket."
2222
gsutil mb gs://$GCLOUD_PROJECT
2323
gsutil defacl set public-read gs://$GCLOUD_PROJECT
2424

25+
echo "Creating bigtable resources."
26+
gcloud alpha bigtable clusters create bigtable-test \
27+
--description="Test cluster" \
28+
--nodes=3 \
29+
--zone=us-central1-c
30+
2531
echo "Creating bigquery resources."
2632
gcloud alpha bigquery datasets create test_dataset
2733
gcloud alpha bigquery datasets create ephemeral_test_dataset
@@ -38,4 +44,4 @@ echo "Creating pubsub resources."
3844
gcloud alpha pubsub topics create gae-mvm-pubsub-topic
3945

4046
echo "To finish setup, follow this link to enable APIs."
41-
echo "https://console.cloud.google.com/flows/enableapi?project=${GCLOUD_PROJECT}&apiid=bigquery,cloudmonitoring,compute_component,datastore,datastore.googleapis.com,dataproc,dns,plus,pubsub,logging,storage_api,vision.googleapis.com"
47+
echo "https://console.cloud.google.com/flows/enableapi?project=${GCLOUD_PROJECT}&apiid=bigtable,bigtableclusteradmin,bigtabletableadmin,bigquery,cloudmonitoring,compute_component,datastore,datastore.googleapis.com,dataproc,dns,plus,pubsub,logging,storage_api,vision.googleapis.com"

testing/resources/test-env.tmpl.sh

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
# Environment variables for system tests.
22
export GCLOUD_PROJECT=your-project-id
33
export CLOUD_STORAGE_BUCKET=$GCLOUD_PROJECT
4+
export BIGTABLE_CLUSTER=bigtable-test
5+
export BIGTABLE_ZONE=us-central1-c
46

57
# Environment variables for App Engine Flexible system tests.
68
export GA_TRACKING_ID=

0 commit comments

Comments
 (0)