From ffc5f176cf106e2180fe5f1475ab24010ff7e1e0 Mon Sep 17 00:00:00 2001 From: Juan Lara Date: Fri, 12 Aug 2022 16:24:29 +0000 Subject: [PATCH] docs(samples): Add an example of using read_time in queries and get() (#342) * Add an example of using read_time in queries and get() * Fix test for query_with_readtime --- samples/snippets/snippets.py | 23 ++++++++++++++++++++++- samples/snippets/snippets_test.py | 6 ++++++ 2 files changed, 28 insertions(+), 1 deletion(-) diff --git a/samples/snippets/snippets.py b/samples/snippets/snippets.py index 40dd5aad..7d2130a8 100644 --- a/samples/snippets/snippets.py +++ b/samples/snippets/snippets.py @@ -12,6 +12,7 @@ # limitations under the License. import argparse +from datetime import datetime, timedelta, timezone from pprint import pprint from google.cloud import datastore # noqa: I100 @@ -56,11 +57,31 @@ def not_in_query(client): return list(query.fetch()) +def query_with_readtime(client): + # [START datastore_snapshot_read] + # Create a read time of 120 seconds in the past + read_time = datetime.now(timezone.utc) - timedelta(seconds=120) + + # Fetch an entity at time read_time + task_key = client.key('Task', 'sampletask') + entity = client.get(task_key, read_time=read_time) + + # Query Task entities at time read_time + query = client.query(kind="Task") + tasks = query.fetch(read_time=read_time, limit=10) + # [END datastore_snapshot_read] + + results = list(tasks) + results.append(entity) + + return results + + def main(project_id): client = datastore.Client(project_id) for name, function in globals().items(): - if name in ("main", "_preamble", "defaultdict") or not callable(function): + if name in ("main", "_preamble", "defaultdict", "datetime", "timezone", "timedelta") or not callable(function): continue print(name) diff --git a/samples/snippets/snippets_test.py b/samples/snippets/snippets_test.py index 27607c07..58e75a59 100644 --- a/samples/snippets/snippets_test.py +++ b/samples/snippets/snippets_test.py @@ -66,3 +66,9 @@ def test_not_in_query(self, client): tasks = snippets.not_in_query(client) client.entities_to_delete.extend(tasks) assert tasks is not None + + @backoff.on_exception(backoff.expo, AssertionError, max_time=240) + def test_query_with_readtime(self, client): + tasks = snippets.query_with_readtime(client) + client.entities_to_delete.extend(tasks) + assert tasks is not None