|
| 1 | +# Copyright 2024 Google LLC |
| 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 | +# [START bigtable_functions_quickstart_asyncio] |
| 16 | +import asyncio |
| 17 | + |
| 18 | +import functions_framework |
| 19 | +from google.cloud.bigtable.data import BigtableDataClientAsync, ReadRowsQuery, RowRange |
| 20 | + |
| 21 | +event_loop = asyncio.new_event_loop() |
| 22 | +asyncio.set_event_loop(event_loop) |
| 23 | + |
| 24 | + |
| 25 | +# Setup: create a shared client within the context of the event loop |
| 26 | +async def create_client(): |
| 27 | + # create client in the asyncio event loop context to |
| 28 | + # give background tasks a chance to initialize |
| 29 | + return BigtableDataClientAsync() |
| 30 | + |
| 31 | + |
| 32 | +client = event_loop.run_until_complete(create_client()) |
| 33 | + |
| 34 | + |
| 35 | +# Actual cloud functions entrypoint, will delegate to the async one |
| 36 | +@functions_framework.http |
| 37 | +def bigtable_read_data(request): |
| 38 | + return event_loop.run_until_complete(_bigtable_read_data_async(request)) |
| 39 | + |
| 40 | + |
| 41 | +# Actual handler |
| 42 | +async def _bigtable_read_data_async(request): |
| 43 | + async with client.get_table( |
| 44 | + request.headers.get("instance_id"), request.headers.get("table_id") |
| 45 | + ) as table: |
| 46 | + |
| 47 | + prefix = "phone#" |
| 48 | + end_key = prefix[:-1] + chr(ord(prefix[-1]) + 1) |
| 49 | + |
| 50 | + outputs = [] |
| 51 | + query = ReadRowsQuery(row_ranges=[RowRange(start_key=prefix, end_key=end_key)]) |
| 52 | + |
| 53 | + async for row in await table.read_rows_stream(query): |
| 54 | + print("%s" % row) |
| 55 | + output = "Rowkey: {}, os_build: {}".format( |
| 56 | + row.row_key.decode("utf-8"), |
| 57 | + row.get_cells("stats_summary", b"os_build")[0].value.decode("utf-8"), |
| 58 | + ) |
| 59 | + outputs.append(output) |
| 60 | + |
| 61 | + return "\n".join(outputs) |
| 62 | + |
| 63 | + |
| 64 | +# [END bigtable_functions_quickstart_asyncio] |
0 commit comments