Skip to content

Commit 93c7930

Browse files
authored
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
1 parent cf49ec3 commit 93c7930

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

packages/google-cloud-datastore/samples/snippets/snippets.py

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
# limitations under the License.
1313

1414
import argparse
15+
from datetime import datetime, timedelta, timezone
1516
from pprint import pprint
1617

1718
from google.cloud import datastore # noqa: I100
@@ -56,11 +57,31 @@ def not_in_query(client):
5657
return list(query.fetch())
5758

5859

60+
def query_with_readtime(client):
61+
# [START datastore_snapshot_read]
62+
# Create a read time of 120 seconds in the past
63+
read_time = datetime.now(timezone.utc) - timedelta(seconds=120)
64+
65+
# Fetch an entity at time read_time
66+
task_key = client.key('Task', 'sampletask')
67+
entity = client.get(task_key, read_time=read_time)
68+
69+
# Query Task entities at time read_time
70+
query = client.query(kind="Task")
71+
tasks = query.fetch(read_time=read_time, limit=10)
72+
# [END datastore_snapshot_read]
73+
74+
results = list(tasks)
75+
results.append(entity)
76+
77+
return results
78+
79+
5980
def main(project_id):
6081
client = datastore.Client(project_id)
6182

6283
for name, function in globals().items():
63-
if name in ("main", "_preamble", "defaultdict") or not callable(function):
84+
if name in ("main", "_preamble", "defaultdict", "datetime", "timezone", "timedelta") or not callable(function):
6485
continue
6586

6687
print(name)

packages/google-cloud-datastore/samples/snippets/snippets_test.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,9 @@ def test_not_in_query(self, client):
6666
tasks = snippets.not_in_query(client)
6767
client.entities_to_delete.extend(tasks)
6868
assert tasks is not None
69+
70+
@backoff.on_exception(backoff.expo, AssertionError, max_time=240)
71+
def test_query_with_readtime(self, client):
72+
tasks = snippets.query_with_readtime(client)
73+
client.entities_to_delete.extend(tasks)
74+
assert tasks is not None

0 commit comments

Comments
 (0)