forked from GoogleCloudPlatform/python-docs-samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
snippets.py
903 lines (660 loc) · 23 KB
/
snippets.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
# Copyright 2016, Google, Inc.
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import argparse
from collections import defaultdict
import datetime
from pprint import pprint
from google.cloud import datastore
import google.cloud.exceptions
def incomplete_key(client):
# [START datastore_incomplete_key]
key = client.key('Task')
# [END datastore_incomplete_key]
return key
def named_key(client):
# [START datastore_named_key]
key = client.key('Task', 'sample_task')
# [END datastore_named_key]
return key
def key_with_parent(client):
# [START datastore_key_with_parent]
key = client.key('TaskList', 'default', 'Task', 'sample_task')
# Alternatively
parent_key = client.key('TaskList', 'default')
key = client.key('Task', 'sample_task', parent=parent_key)
# [END datastore_key_with_parent]
return key
def key_with_multilevel_parent(client):
# [START datastore_key_with_multilevel_parent]
key = client.key(
'User', 'alice',
'TaskList', 'default',
'Task', 'sample_task')
# [END datastore_key_with_multilevel_parent]
return key
def basic_entity(client):
# [START datastore_basic_entity]
task = datastore.Entity(client.key('Task'))
task.update({
'category': 'Personal',
'done': False,
'priority': 4,
'description': 'Learn Cloud Datastore'
})
# [END datastore_basic_entity]
return task
def entity_with_parent(client):
# [START datastore_entity_with_parent]
key_with_parent = client.key(
'TaskList', 'default', 'Task', 'sample_task')
task = datastore.Entity(key=key_with_parent)
task.update({
'category': 'Personal',
'done': False,
'priority': 4,
'description': 'Learn Cloud Datastore'
})
# [END datastore_entity_with_parent]
return task
def properties(client):
key = client.key('Task')
# [START datastore_properties]
task = datastore.Entity(
key,
exclude_from_indexes=['description'])
task.update({
'category': 'Personal',
'description': 'Learn Cloud Datastore',
'created': datetime.datetime.utcnow(),
'done': False,
'priority': 4,
'percent_complete': 10.5,
})
# [END datastore_properties]
return task
def array_value(client):
key = client.key('Task')
# [START datastore_array_value]
task = datastore.Entity(key)
task.update({
'tags': [
'fun',
'programming'
],
'collaborators': [
'alice',
'bob'
]
})
# [END datastore_array_value]
return task
def upsert(client):
# [START datastore_upsert]
complete_key = client.key('Task', 'sample_task')
task = datastore.Entity(key=complete_key)
task.update({
'category': 'Personal',
'done': False,
'priority': 4,
'description': 'Learn Cloud Datastore'
})
client.put(task)
# [END datastore_upsert]
return task
def insert(client):
# [START datastore_insert]
with client.transaction():
incomplete_key = client.key('Task')
task = datastore.Entity(key=incomplete_key)
task.update({
'category': 'Personal',
'done': False,
'priority': 4,
'description': 'Learn Cloud Datastore'
})
client.put(task)
# [END datastore_insert]
return task
def update(client):
# Create the entity we're going to update.
upsert(client)
# [START datastore_update]
with client.transaction():
key = client.key('Task', 'sample_task')
task = client.get(key)
task['done'] = True
client.put(task)
# [END datastore_update]
return task
def lookup(client):
# Create the entity that we're going to look up.
upsert(client)
# [START datastore_lookup]
key = client.key('Task', 'sample_task')
task = client.get(key)
# [END datastore_lookup]
return task
def delete(client):
# Create the entity we're going to delete.
upsert(client)
# [START datastore_delete]
key = client.key('Task', 'sample_task')
client.delete(key)
# [END datastore_delete]
return key
def batch_upsert(client):
# [START datastore_batch_upsert]
task1 = datastore.Entity(client.key('Task', 1))
task1.update({
'category': 'Personal',
'done': False,
'priority': 4,
'description': 'Learn Cloud Datastore'
})
task2 = datastore.Entity(client.key('Task', 2))
task2.update({
'category': 'Work',
'done': False,
'priority': 8,
'description': 'Integrate Cloud Datastore'
})
client.put_multi([task1, task2])
# [END datastore_batch_upsert]
return task1, task2
def batch_lookup(client):
# Create the entities we will lookup.
batch_upsert(client)
keys = [
client.key('Task', 1),
client.key('Task', 2)
]
# [START datastore_batch_lookup]
tasks = client.get_multi(keys)
# [END datastore_batch_lookup]
return tasks
def batch_delete(client):
# Create the entities we will delete.
batch_upsert(client)
keys = [
client.key('Task', 1),
client.key('Task', 2)
]
# [START datastore_batch_delete]
client.delete_multi(keys)
# [END datastore_batch_delete]
return keys
def unindexed_property_query(client):
# Create the entity that we're going to query.
upsert(client)
# [START datastore_unindexed_property_query]
query = client.query(kind='Task')
query.add_filter('description', '=', 'Learn Cloud Datastore')
# [END datastore_unindexed_property_query]
return list(query.fetch())
def basic_query(client):
# Create the entity that we're going to query.
upsert(client)
# [START datastore_basic_query]
query = client.query(kind='Task')
query.add_filter('done', '=', False)
query.add_filter('priority', '>=', 4)
query.order = ['-priority']
# [END datastore_basic_query]
return list(query.fetch())
def projection_query(client):
# Create the entity that we're going to query.
task = datastore.Entity(client.key('Task'))
task.update({
'category': 'Personal',
'done': False,
'priority': 4,
'description': 'Learn Cloud Datastore',
'percent_complete': 0.5
})
client.put(task)
# [START datastore_projection_query]
query = client.query(kind='Task')
query.projection = ['priority', 'percent_complete']
# [END datastore_projection_query]
# [START datastore_run_query_projection]
priorities = []
percent_completes = []
for task in query.fetch():
priorities.append(task['priority'])
percent_completes.append(task['percent_complete'])
# [END datastore_run_query_projection]
return priorities, percent_completes
def ancestor_query(client):
task = datastore.Entity(
client.key('TaskList', 'default', 'Task'))
task.update({
'category': 'Personal',
'description': 'Learn Cloud Datastore',
})
client.put(task)
# [START datastore_ancestor_query]
# Query filters are omitted in this example as any ancestor queries with a
# non-key filter require a composite index.
ancestor = client.key('TaskList', 'default')
query = client.query(kind='Task', ancestor=ancestor)
# [END datastore_ancestor_query]
return list(query.fetch())
def run_query(client):
# [START datastore_run_query]
query = client.query()
results = list(query.fetch())
# [END datastore_run_query]
return results
def limit(client):
# [START datastore_limit]
query = client.query()
tasks = list(query.fetch(limit=5))
# [END datastore_limit]
return tasks
def cursor_paging(client):
# [START datastore_cursor_paging]
def get_one_page_of_tasks(cursor=None):
query = client.query(kind='Task')
query_iter = query.fetch(start_cursor=cursor, limit=5)
page = next(query_iter.pages)
tasks = list(page)
next_cursor = query_iter.next_page_token
return tasks, next_cursor
# [END datastore_cursor_paging]
page_one, cursor_one = get_one_page_of_tasks()
page_two, cursor_two = get_one_page_of_tasks(cursor=cursor_one)
return page_one, cursor_one, page_two, cursor_two
def property_filter(client):
# Create the entity that we're going to query.
upsert(client)
# [START datastore_property_filter]
query = client.query(kind='Task')
query.add_filter('done', '=', False)
# [END datastore_property_filter]
return list(query.fetch())
def composite_filter(client):
# Create the entity that we're going to query.
upsert(client)
# [START datastore_composite_filter]
query = client.query(kind='Task')
query.add_filter('done', '=', False)
query.add_filter('priority', '=', 4)
# [END datastore_composite_filter]
return list(query.fetch())
def key_filter(client):
# Create the entity that we're going to query.
upsert(client)
# [START datastore_key_filter]
query = client.query(kind='Task')
first_key = client.key('Task', 'first_task')
# key_filter(key, op) translates to add_filter('__key__', op, key).
query.key_filter(first_key, '>')
# [END datastore_key_filter]
return list(query.fetch())
def ascending_sort(client):
# Create the entity that we're going to query.
task = upsert(client)
task['created'] = datetime.datetime.utcnow()
client.put(task)
# [START datastore_ascending_sort]
query = client.query(kind='Task')
query.order = ['created']
# [END datastore_ascending_sort]
return list(query.fetch())
def descending_sort(client):
# Create the entity that we're going to query.
task = upsert(client)
task['created'] = datetime.datetime.utcnow()
client.put(task)
# [START datastore_descending_sort]
query = client.query(kind='Task')
query.order = ['-created']
# [END datastore_descending_sort]
return list(query.fetch())
def multi_sort(client):
# Create the entity that we're going to query.
task = upsert(client)
task['created'] = datetime.datetime.utcnow()
client.put(task)
# [START datastore_multi_sort]
query = client.query(kind='Task')
query.order = [
'-priority',
'created'
]
# [END datastore_multi_sort]
return list(query.fetch())
def keys_only_query(client):
# Create the entity that we're going to query.
upsert(client)
# [START datastore_keys_only_query]
query = client.query()
query.keys_only()
# [END datastore_keys_only_query]
keys = list([entity.key for entity in query.fetch(limit=10)])
return keys
def distinct_on_query(client):
# Create the entity that we're going to query.
upsert(client)
# [START datastore_distinct_on_query]
query = client.query(kind='Task')
query.distinct_on = ['category']
query.order = ['category', 'priority']
# [END datastore_distinct_on_query]
return list(query.fetch())
def kindless_query(client):
# Create the entity that we're going to query.
upsert(client)
last_seen_key = client.key('Task', 'a')
# [START datastore_kindless_query]
query = client.query()
query.key_filter(last_seen_key, '>')
# [END datastore_kindless_query]
return list(query.fetch())
def inequality_range(client):
# [START datastore_inequality_range]
start_date = datetime.datetime(1990, 1, 1)
end_date = datetime.datetime(2000, 1, 1)
query = client.query(kind='Task')
query.add_filter(
'created', '>', start_date)
query.add_filter(
'created', '<', end_date)
# [END datastore_inequality_range]
return list(query.fetch())
def inequality_invalid(client):
try:
# [START datastore_inequality_invalid]
start_date = datetime.datetime(1990, 1, 1)
query = client.query(kind='Task')
query.add_filter(
'created', '>', start_date)
query.add_filter(
'priority', '>', 3)
# [END datastore_inequality_invalid]
return list(query.fetch())
except (google.cloud.exceptions.BadRequest,
google.cloud.exceptions.GrpcRendezvous):
pass
def equal_and_inequality_range(client):
# [START datastore_equal_and_inequality_range]
start_date = datetime.datetime(1990, 1, 1)
end_date = datetime.datetime(2000, 12, 31, 23, 59, 59)
query = client.query(kind='Task')
query.add_filter('priority', '=', 4)
query.add_filter('done', '=', False)
query.add_filter(
'created', '>', start_date)
query.add_filter(
'created', '<', end_date)
# [END datastore_equal_and_inequality_range]
return list(query.fetch())
def inequality_sort(client):
# [START datastore_inequality_sort]
query = client.query(kind='Task')
query.add_filter('priority', '>', 3)
query.order = ['priority', 'created']
# [END datastore_inequality_sort]
return list(query.fetch())
def inequality_sort_invalid_not_same(client):
try:
# [START datastore_inequality_sort_invalid_not_same]
query = client.query(kind='Task')
query.add_filter('priority', '>', 3)
query.order = ['created']
# [END datastore_inequality_sort_invalid_not_same]
return list(query.fetch())
except (google.cloud.exceptions.BadRequest,
google.cloud.exceptions.GrpcRendezvous):
pass
def inequality_sort_invalid_not_first(client):
try:
# [START datastore_inequality_sort_invalid_not_first]
query = client.query(kind='Task')
query.add_filter('priority', '>', 3)
query.order = ['created', 'priority']
# [END datastore_inequality_sort_invalid_not_first]
return list(query.fetch())
except (google.cloud.exceptions.BadRequest,
google.cloud.exceptions.GrpcRendezvous):
pass
def array_value_inequality_range(client):
# [START datastore_array_value_inequality_range]
query = client.query(kind='Task')
query.add_filter('tag', '>', 'learn')
query.add_filter('tag', '<', 'math')
# [END datastore_array_value_inequality_range]
return list(query.fetch())
def array_value_equality(client):
# [START datastore_array_value_equality]
query = client.query(kind='Task')
query.add_filter('tag', '=', 'fun')
query.add_filter('tag', '=', 'programming')
# [END datastore_array_value_equality]
return list(query.fetch())
def exploding_properties(client):
# [START datastore_exploding_properties]
task = datastore.Entity(client.key('Task'))
task.update({
'tags': [
'fun',
'programming',
'learn'
],
'collaborators': [
'alice',
'bob',
'charlie'
],
'created': datetime.datetime.utcnow()
})
# [END datastore_exploding_properties]
return task
def transactional_update(client):
# Create the entities we're going to manipulate
account1 = datastore.Entity(client.key('Account'))
account1['balance'] = 100
account2 = datastore.Entity(client.key('Account'))
account2['balance'] = 100
client.put_multi([account1, account2])
# [START datastore_transactional_update]
def transfer_funds(client, from_key, to_key, amount):
with client.transaction():
from_account = client.get(from_key)
to_account = client.get(to_key)
from_account['balance'] -= amount
to_account['balance'] += amount
client.put_multi([from_account, to_account])
# [END datastore_transactional_update]
# [START datastore_transactional_retry]
for _ in range(5):
try:
transfer_funds(client, account1.key, account2.key, 50)
break
except google.cloud.exceptions.Conflict:
continue
else:
print('Transaction failed.')
# [END datastore_transactional_retry]
return account1.key, account2.key
def transactional_get_or_create(client):
# [START datastore_transactional_get_or_create]
with client.transaction():
key = client.key('Task', datetime.datetime.utcnow().isoformat())
task = client.get(key)
if not task:
task = datastore.Entity(key)
task.update({
'description': 'Example task'
})
client.put(task)
return task
# [END datastore_transactional_get_or_create]
def transactional_single_entity_group_read_only(client):
client.put_multi([
datastore.Entity(key=client.key('TaskList', 'default')),
datastore.Entity(key=client.key('TaskList', 'default', 'Task', 1))
])
# [START datastore_transactional_single_entity_group_read_only]
with client.transaction(read_only=True):
task_list_key = client.key('TaskList', 'default')
task_list = client.get(task_list_key)
query = client.query(kind='Task', ancestor=task_list_key)
tasks_in_list = list(query.fetch())
return task_list, tasks_in_list
# [END datastore_transactional_single_entity_group_read_only]
def namespace_run_query(client):
# Create an entity in another namespace.
task = datastore.Entity(
client.key('Task', 'sample-task', namespace='google'))
client.put(task)
# [START datastore_namespace_run_query]
# All namespaces
query = client.query(kind='__namespace__')
query.keys_only()
all_namespaces = [entity.key.id_or_name for entity in query.fetch()]
# Filtered namespaces
start_namespace = client.key('__namespace__', 'g')
end_namespace = client.key('__namespace__', 'h')
query = client.query(kind='__namespace__')
query.key_filter(start_namespace, '>=')
query.key_filter(end_namespace, '<')
filtered_namespaces = [entity.key.id_or_name for entity in query.fetch()]
# [END datastore_namespace_run_query]
return all_namespaces, filtered_namespaces
def kind_run_query(client):
# Create the entity that we're going to query.
upsert(client)
# [START datastore_kind_run_query]
query = client.query(kind='__kind__')
query.keys_only()
kinds = [entity.key.id_or_name for entity in query.fetch()]
# [END datastore_kind_run_query]
return kinds
def property_run_query(client):
# Create the entity that we're going to query.
upsert(client)
# [START datastore_property_run_query]
query = client.query(kind='__property__')
query.keys_only()
properties_by_kind = defaultdict(list)
for entity in query.fetch():
kind = entity.key.parent.name
property_ = entity.key.name
properties_by_kind[kind].append(property_)
# [END datastore_property_run_query]
return properties_by_kind
def property_by_kind_run_query(client):
# Create the entity that we're going to query.
upsert(client)
# [START datastore_property_by_kind_run_query]
ancestor = client.key('__kind__', 'Task')
query = client.query(kind='__property__', ancestor=ancestor)
representations_by_property = {}
for entity in query.fetch():
property_name = entity.key.name
property_types = entity['property_representation']
representations_by_property[property_name] = property_types
# [END datastore_property_by_kind_run_query]
return representations_by_property
def eventual_consistent_query(client):
# [START datastore_eventual_consistent_query]
query = client.query(kind='Task')
query.fetch(eventual=True)
# [END datastore_eventual_consistent_query]
pass
def index_merge_queries(client):
# Create a Photo entity to query
photo = datastore.Entity(client.key('Photo', 'sample_photo'))
photo.update({
'owner_id': 'user1234',
'size': 2,
'coloration': 2,
'tag': ['family', 'outside', 'camping']
})
client.put(photo)
# Sample queries using built-in indexes
queries = []
# [START datastore_built_in_index_queries]
query_owner_id = client.query(
kind='Photo',
filters=[('owner_id', '=', 'user1234')])
query_size = client.query(
kind='Photo',
filters=[('size', '=', 2)])
query_coloration = client.query(
kind='Photo',
filters=[('coloration', '=', 2)])
# [END datastore_built_in_index_queries]
queries.append(query_owner_id)
queries.append(query_size)
queries.append(query_coloration)
# [START datastore_merged_index_query]
query_all_properties = client.query(
kind='Photo',
filters=[('owner_id', '=', 'user1234'),
('size', '=', 2),
('coloration', '=', 2),
('tag', '=', 'family')])
# [END datastore_merged_index_query]
queries.append(query_all_properties)
# [START datastore_merged_index_tag_queries]
query_tag = client.query(
kind='Photo',
filters=[('tag', '=', 'family'),
('tag', '=', 'outside'),
('tag', '=', 'camping')])
query_owner_size_color_tags = client.query(
kind='Photo',
filters=[('owner_id', '=', 'user1234'),
('size', '=', 2),
('coloration', '=', 2),
('tag', '=', 'family'),
('tag', '=', 'outside'),
('tag', '=', 'camping')])
# [END datastore_merged_index_tag_queries]
queries.append(query_tag)
queries.append(query_owner_size_color_tags)
# [START datastore_owner_size_tag_query]
query_owner_size_tag = client.query(
kind='Photo',
filters=[('owner_id', '=', 'username'),
('size', '=', 2),
('tag', '=', 'family')])
# [END datastore_owner_size_tag_query]
queries.append(query_owner_size_tag)
# [START datastore_size_coloration_query]
query_size_coloration = client.query(
kind='Photo',
filters=[('size', '=', 2),
('coloration', '=', 1)])
# [END datastore_size_coloration_query]
queries.append(query_size_coloration)
results = []
for query in queries:
results.append(query.fetch())
return results
def main(project_id):
client = datastore.Client(project_id)
for name, function in globals().iteritems():
if name in ('main', 'defaultdict') or not callable(function):
continue
print(name)
pprint(function(client))
print('\n-----------------\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser(
description='Demonstrates datastore API operations.')
parser.add_argument('project_id', help='Your cloud project ID.')
args = parser.parse_args()
main(args.project_id)