Skip to content

Commit 39c08fd

Browse files
author
Jerjou Cheng
committed
Move ndb entities code snippets into github
1 parent ac5e73a commit 39c08fd

File tree

3 files changed

+469
-0
lines changed

3 files changed

+469
-0
lines changed

appengine/ndb/entities/README.md

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
## App Engine Datastore NDB Entities Samples
2+
3+
This contains snippets used in the NDB entity documentation, demonstrating
4+
various operation on ndb entities.
5+
6+
<!-- auto-doc-link -->
7+
These samples are used on the following documentation page:
8+
9+
> https://cloud.google.com/appengine/docs/python/ndb/entities
10+
11+
<!-- end-auto-doc-link -->

appengine/ndb/entities/snippets.py

Lines changed: 263 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,263 @@
1+
# Copyright 2016 Google Inc. All rights reserved.
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+
from google.appengine.ext import ndb
16+
17+
18+
class Account(ndb.Model):
19+
username = ndb.StringProperty()
20+
userid = ndb.IntegerProperty()
21+
email = ndb.StringProperty()
22+
23+
24+
def create_model_using_keyword_arguments():
25+
sandy = Account(
26+
username='Sandy', userid=123, email='[email protected]')
27+
return sandy
28+
29+
30+
def create_model_using_attributes():
31+
sandy = Account()
32+
sandy.username = 'Sandy'
33+
sandy.userid = 123
34+
sandy.email = '[email protected]'
35+
return sandy
36+
37+
38+
def demonstrate_model_constructor_type_checking():
39+
bad = Account(
40+
username='Sandy', userid='not integer') # raises an exception
41+
return bad
42+
43+
44+
def dmonstrate_model_attribute_type_checking(sandy):
45+
sandy.username = 42 # raises an exception
46+
47+
48+
def save_model(sandy):
49+
sandy_key = sandy.put()
50+
return sandy_key
51+
52+
53+
def get_url_safe_key(sandy_key):
54+
url_string = sandy_key.urlsafe()
55+
return url_string
56+
57+
58+
def get_model_from_url_safe_key(url_string):
59+
sandy_key = ndb.Key(urlsafe=url_string)
60+
sandy = sandy_key.get()
61+
return sandy
62+
63+
64+
def get_key_and_numeric_id_from_url_safe_key(url_string):
65+
key = ndb.Key(urlsafe=url_string)
66+
kind_string = key.kind()
67+
ident = key.id()
68+
return key, ident, kind_string
69+
70+
71+
def update_model_from_key(key):
72+
sandy = key.get()
73+
sandy.email = '[email protected]'
74+
sandy.put()
75+
76+
77+
def delete_model(sandy):
78+
sandy.key.delete()
79+
80+
81+
def create_model_with_named_key():
82+
account = Account(
83+
username='Sandy', userid=1234, email='[email protected]',
84+
85+
86+
return account.key.id() # returns '[email protected]'
87+
88+
89+
def set_key_directly(account):
90+
account.key = ndb.Key('Account', '[email protected]')
91+
92+
# You can also use the model class object itself, rather than its name,
93+
# to specify the entity's kind:
94+
account.key = ndb.Key(Account, '[email protected]')
95+
96+
97+
def create_model_with_generated_id():
98+
# note: no id kwarg
99+
account = Account(username='Sandy', userid=1234, email='[email protected]')
100+
account.put()
101+
# Account.key will now have a key of the form: ndb.Key(Account, 71321839)
102+
# where the value 71321839 was generated by Datastore for us.
103+
return account
104+
105+
106+
class Revision(ndb.Model):
107+
message_text = ndb.StringProperty()
108+
109+
110+
def demonstrate_models_with_parent_hierarchy():
111+
ndb.Key('Account', '[email protected]', 'Message', 123, 'Revision', '1')
112+
ndb.Key('Account', '[email protected]', 'Message', 123, 'Revision', '2')
113+
ndb.Key('Account', '[email protected]', 'Message', 456, 'Revision', '1')
114+
ndb.Key('Account', '[email protected]', 'Message', 789, 'Revision', '2')
115+
116+
117+
def equivalent_ways_to_define_key_with_parent():
118+
ndb.Key('Account', '[email protected]', 'Message', 123, 'Revision', '1')
119+
120+
ndb.Key('Revision', '1', parent=ndb.Key(
121+
'Account', '[email protected]', 'Message', 123))
122+
123+
ndb.Key('Revision', '1', parent=ndb.Key(
124+
'Message', 123, parent=ndb.Key('Account', '[email protected]')))
125+
126+
sandy_key = ndb.Key(Account, '[email protected]')
127+
return sandy_key
128+
129+
130+
def create_model_with_parent_keys():
131+
account_key = ndb.Key(Account, '[email protected]')
132+
133+
# Ask Datastore to allocate an ID.
134+
new_id = ndb.Model.allocate_ids(size=1, parent=account_key)[0]
135+
136+
# Datastore returns us an integer ID that we can use to create the message
137+
# key
138+
message_key = ndb.Key('Message', new_id, parent=account_key)
139+
140+
# Now we can put the message into Datastore
141+
initial_revision = Revision(
142+
message_text='Hello', id='1', parent=message_key)
143+
initial_revision.put()
144+
145+
return initial_revision
146+
147+
148+
def get_parent_key_of_model(initial_revision):
149+
message_key = initial_revision.key.parent()
150+
return message_key
151+
152+
153+
def operate_on_multiple_keys_at_once(list_of_entities):
154+
list_of_keys = ndb.put_multi(list_of_entities)
155+
list_of_entities = ndb.get_multi(list_of_keys)
156+
ndb.delete_multi(list_of_keys)
157+
158+
159+
class Mine(ndb.Expando):
160+
pass
161+
162+
163+
def create_expando_model():
164+
e = Mine()
165+
e.foo = 1
166+
e.bar = 'blah'
167+
e.tags = ['exp', 'and', 'oh']
168+
e.put()
169+
170+
return e
171+
172+
173+
def get_properties_defined_on_expando(e):
174+
return e._properties
175+
# {
176+
# 'foo': GenericProperty('foo'),
177+
# 'bar': GenericProperty('bar'),
178+
# 'tags': GenericProperty('tags', repeated=True)
179+
# }
180+
181+
182+
class FlexEmployee(ndb.Expando):
183+
name = ndb.StringProperty()
184+
age = ndb.IntegerProperty()
185+
186+
187+
def create_expando_model_with_defined_properties():
188+
employee = FlexEmployee(name='Sandy', location='SF')
189+
return employee
190+
191+
192+
class Specialized(ndb.Expando):
193+
_default_indexed = False
194+
195+
196+
def create_expando_model_that_isnt_indexed_by_default():
197+
e = Specialized(foo='a', bar=['b'])
198+
return e._properties
199+
# {
200+
# 'foo': GenericProperty('foo', indexed=False),
201+
# 'bar': GenericProperty('bar', indexed=False, repeated=True)
202+
# }
203+
204+
205+
def demonstrate_wrong_way_to_query_expando():
206+
FlexEmployee.query(FlexEmployee.location == 'SF')
207+
208+
209+
def demonstrate_right_way_to_query_expando():
210+
FlexEmployee.query(ndb.GenericProperty('location') == 'SF')
211+
212+
213+
notification = None
214+
215+
216+
def _notify(message):
217+
global notification
218+
notification = message
219+
220+
221+
class Friend(ndb.Model):
222+
name = ndb.StringProperty()
223+
224+
def _pre_put_hook(self):
225+
_notify('Gee wiz I have a new friend!')
226+
227+
@classmethod
228+
def _post_delete_hook(cls, key, future):
229+
_notify('I have found occasion to rethink our friendship.')
230+
231+
232+
def demonstrate_model_put_and_delete_hooks():
233+
f = Friend()
234+
f.name = 'Carole King'
235+
f.put() # _pre_put_hook is called
236+
yield f
237+
fut = f.key.delete_async() # _post_delete_hook not yet called
238+
fut.get_result() # _post_delete_hook is called
239+
yield f
240+
241+
242+
class MyModel(ndb.Model):
243+
pass
244+
245+
246+
def reserve_model_ids():
247+
first, last = MyModel.allocate_ids(100)
248+
return first, last
249+
250+
251+
def reserve_model_ids_with_a_parent(p):
252+
first, last = MyModel.allocate_ids(100, parent=p)
253+
return first, last
254+
255+
256+
def construct_keys_from_range_of_reserved_ids(first, last):
257+
keys = [ndb.Key(MyModel, id) for id in range(first, last+1)]
258+
return keys
259+
260+
261+
def reserve_model_ids_up_to(N):
262+
first, last = MyModel.allocate_ids(max=N)
263+
return first, last

0 commit comments

Comments
 (0)