Skip to content
This repository was archived by the owner on Apr 1, 2026. It is now read-only.

Commit 291d3ea

Browse files
committed
feat: Add async sample for incrementing a value
1 parent 72dfdc4 commit 291d3ea

2 files changed

Lines changed: 41 additions & 1 deletion

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# [START bigtable_write_increment_async]
2+
from google.cloud.bigtable.data import BigtableDataClientAsync
3+
from google.cloud.bigtable.data.mutations import AddToCell, RowMutationEntry
4+
from google.cloud.bigtable.data.exceptions import MutationsExceptionGroup
5+
6+
async def write_increment_async(project_id, instance_id, table_id):
7+
"""Increments a value in a Bigtable table using the async client."""
8+
async with BigtableDataClientAsync(project=project_id) as client:
9+
table = client.get_table(instance_id, table_id)
10+
row_key = "unique_device_ids_1"
11+
try:
12+
async with table.mutations_batcher() as batcher:
13+
# The AddToCell mutation increments the value of a cell.
14+
# The value must be a positive or negative integer.
15+
reading = AddToCell(
16+
family="counters",
17+
qualifier="odometer",
18+
value=32304
19+
)
20+
await batcher.append(RowMutationEntry(row_key.encode("utf-8"), [reading]))
21+
except MutationsExceptionGroup as e:
22+
# MutationsExceptionGroup contains a FailedMutationEntryError for
23+
# each mutation that failed.
24+
for sub_exception in e.exceptions:
25+
failed_entry: RowMutationEntry = sub_exception.entry
26+
cause: Exception = sub_exception.__cause__
27+
print(
28+
f"Failed mutation for row {failed_entry.row_key!r} with error: {cause!r}"
29+
)
30+
# [END bigtable_write_increment_async]

samples/snippets/writes/writes_test.py

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,15 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
import asyncio
1516
import os
17+
import uuid
1618

1719
import backoff
1820
from google.api_core.exceptions import DeadlineExceeded
1921
import pytest
20-
import uuid
2122

23+
from .write_increment_async import write_increment_async
2224
from .write_batch import write_batch
2325
from .write_conditionally import write_conditional
2426
from .write_increment import write_increment
@@ -71,3 +73,11 @@ def _write_batch():
7173
_write_batch()
7274
out, _ = capsys.readouterr()
7375
assert "Successfully wrote 2 rows" in out
76+
77+
@backoff.on_exception(backoff.expo, DeadlineExceeded, max_time=60)
78+
def _write_increment_async():
79+
asyncio.run(write_increment_async(PROJECT, BIGTABLE_INSTANCE, table_id))
80+
81+
_write_increment_async()
82+
out, _ = capsys.readouterr()
83+
assert "Successfully incremented row" in out

0 commit comments

Comments
 (0)