-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathentity.py
266 lines (206 loc) · 9.29 KB
/
entity.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
# Copyright 2014 Google Inc. All rights reserved.
#
# 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.
"""Class for representing a single entity in the Cloud Datastore."""
from gcloud.datastore import _implicit_environ
from gcloud.datastore.key import Key
class NoKey(RuntimeError):
"""Exception raised by Entity methods which require a key."""
class NoDataset(RuntimeError):
"""Exception raised by Entity methods which require a dataset."""
class Entity(dict):
"""Entities are akin to rows in a relational database
An entity storing the actual instance of data.
Each entity is officially represented with a
:class:`gcloud.datastore.key.Key` class, however it is possible that
you might create an Entity with only a partial Key (that is, a Key
with a Kind, and possibly a parent, but without an ID). In such a
case, the datastore service will automatically assign an ID to the
partial key.
Entities in this API act like dictionaries with extras built in that
allow you to delete or persist the data stored on the entity.
Entities are mutable and act like a subclass of a dictionary.
This means you could take an existing entity and change the key
to duplicate the object.
Use :func:`gcloud.datastore.dataset.Dataset.get_entity`
to retrieve an existing entity.
>>> dataset.get_entity(key)
<Entity[{'kind': 'EntityKind', id: 1234}] {'property': 'value'}>
You can the set values on the entity just like you would on any
other dictionary.
>>> entity['age'] = 20
>>> entity['name'] = 'JJ'
>>> entity
<Entity[{'kind': 'EntityKind', id: 1234}] {'age': 20, 'name': 'JJ'}>
And you can convert an entity to a regular Python dictionary with the
`dict` builtin:
>>> dict(entity)
{'age': 20, 'name': 'JJ'}
.. note::
When saving an entity to the backend, values which are "text"
('unicode' in Python2, 'str' in Python3) will be saved using
the 'text_value' field, after being encoded to UTF-8. When
retrieved from the back-end, such values will be decoded to "text"
again. Values which are "bytes" ('str' in Python2, 'bytes' in
Python3), will be saved using the 'blob_value' field, without
any decoding / encoding step.
:type dataset: :class:`gcloud.datastore.dataset.Dataset`
:param dataset: The dataset in which this entity belongs.
:type kind: string
:param kind: The kind of entity this is, akin to a table name in a
relational database.
:type dataset: :class:`gcloud.datastore.dataset.Dataset`, or None
:param dataset: the Dataset instance associated with this entity.
:type kind: str
:param kind: the "kind" of the entity (see
https://cloud.google.com/datastore/docs/concepts/entities#Datastore_Kinds_and_identifiers)
:param exclude_from_indexes: names of fields whose values are not to be
indexed for this entity.
"""
def __init__(self, dataset=None, kind=None, exclude_from_indexes=()):
super(Entity, self).__init__()
# Does not inherit directly from object, so we don't use
# _implicit_environ._DatastoreBase to avoid split MRO.
self._dataset = dataset or _implicit_environ.DATASET
if kind:
self._key = Key(kind, dataset_id=self.dataset().id())
else:
self._key = None
self._exclude_from_indexes = set(exclude_from_indexes)
def dataset(self):
"""Get the :class:`.dataset.Dataset` in which this entity belongs.
.. note::
This is based on the :class:`gcloud.datastore.key.Key` set on the
entity. That means that if you have no key set, the dataset might
be `None`. It also means that if you change the key on the entity,
this will refer to that key's dataset.
:rtype: :class:`gcloud.datastore.dataset.Dataset`
:returns: The Dataset containing the entity if there is a key,
else None.
"""
return self._dataset
def key(self, key=None):
"""Get or set the :class:`.datastore.key.Key` on the current entity.
:type key: :class:`glcouddatastore.key.Key`
:param key: The key you want to set on the entity.
:rtype: :class:`gcloud.datastore.key.Key` or :class:`Entity`.
:returns: Either the current key (on get) or the current
object (on set).
>>> entity.key(my_other_key) # This returns the original entity.
<Entity[{'kind': 'OtherKeyKind', 'id': 1234}] {'property': 'value'}>
>>> entity.key() # This returns the key.
<Key[{'kind': 'OtherKeyKind', 'id': 1234}]>
"""
if key is not None:
self._key = key
return self
else:
return self._key
def kind(self):
"""Get the kind of the current entity.
.. note::
This relies entirely on the :class:`gcloud.datastore.key.Key`
set on the entity. That means that we're not storing the kind
of the entity at all, just the properties and a pointer to a
Key which knows its Kind.
"""
if self._key:
return self._key.kind
def exclude_from_indexes(self):
"""Names of fields which are *not* to be indexed for this entity.
:rtype: sequence of field names
"""
return frozenset(self._exclude_from_indexes)
@classmethod
def from_key(cls, key, dataset=None):
"""Create entity based on :class:`.datastore.key.Key`.
.. note:: This is a factory method.
:type key: :class:`gcloud.datastore.key.Key`
:param key: The key for the entity.
:returns: The :class:`Entity` derived from the
:class:`gcloud.datastore.key.Key`.
"""
return cls(dataset).key(key)
@property
def _must_key(self):
"""Return our key, or raise NoKey if not set.
:rtype: :class:`gcloud.datastore.key.Key`.
:returns: our key
:raises: NoKey if key is None
"""
if self._key is None:
raise NoKey()
return self._key
@property
def _must_dataset(self):
"""Return our dataset, or raise NoDataset if not set.
:rtype: :class:`gcloud.datastore.key.Key`.
:returns: our key
:raises: NoDataset if key is None
"""
if self._dataset is None:
raise NoDataset()
return self._dataset
def reload(self):
"""Reloads the contents of this entity from the datastore.
This method takes the :class:`gcloud.datastore.key.Key`, loads all
properties from the Cloud Datastore, and sets the updated properties on
the current object.
.. warning::
This will override any existing properties if a different value
exists remotely, however it will *not* override any properties that
exist only locally.
"""
key = self._must_key
connection = self._must_dataset.connection()
entity = key.get(connection=connection)
if entity:
self.update(entity)
return self
def save(self):
"""Save the entity in the Cloud Datastore.
.. note::
Any existing properties for the entity will be replaced by those
currently set on this instance. Already-stored properties which do
not correspond to keys set on this instance will be removed from
the datastore.
.. note::
Property values which are "text" ('unicode' in Python2, 'str' in
Python3) map to 'string_value' in the datastore; values which are
"bytes" ('str' in Python2, 'bytes' in Python3) map to 'blob_value'.
:rtype: :class:`gcloud.datastore.entity.Entity`
:returns: The entity with a possibly updated Key.
"""
key = self._must_key
dataset = self._must_dataset
connection = dataset.connection()
assigned, new_id = connection.save_entity(
dataset_id=dataset.id(),
key_pb=key.to_protobuf(),
properties=dict(self),
exclude_from_indexes=self.exclude_from_indexes())
# If we are in a transaction and the current entity needs an
# automatically assigned ID, tell the transaction where to put that.
transaction = connection.transaction()
if transaction and key.is_partial:
transaction.add_auto_id_entity(self)
if assigned:
# Update the key (which may have been altered).
self.key(self.key().completed_key(new_id))
return self
def __repr__(self):
if self._key:
return '<Entity%s %s>' % (self._key.path,
super(Entity, self).__repr__())
else:
return '<Entity %s>' % (super(Entity, self).__repr__())