Skip to content

Commit

Permalink
docs(samples): Add an example of using read_time in queries and get() (
Browse files Browse the repository at this point in the history
…#342)

* Add an example of using read_time in queries and get()

* Fix test for query_with_readtime
  • Loading branch information
jlara310 committed Aug 12, 2022
1 parent de13860 commit ffc5f17
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
23 changes: 22 additions & 1 deletion samples/snippets/snippets.py
Expand Up @@ -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
Expand Down Expand Up @@ -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)
Expand Down
6 changes: 6 additions & 0 deletions samples/snippets/snippets_test.py
Expand Up @@ -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

0 comments on commit ffc5f17

Please sign in to comment.