-
Notifications
You must be signed in to change notification settings - Fork 1.5k
/
Copy pathkey.py
153 lines (122 loc) · 3.8 KB
/
key.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
import copy
from itertools import izip
from gcloud.datastore import datastore_v1_pb2 as datastore_pb
from gcloud.datastore.dataset import Dataset
class Key(object):
"""
An immutable representation of a datastore Key.
"""
def __init__(self, dataset=None, namespace=None, path=None):
self._dataset = dataset
self._namespace = namespace
self._path = path or [{'kind': ''}]
def _clone(self):
"""Duplicates the Key.
We make a shallow copy of the :class:`gcloud.datastore.dataset.Dataset`
because it holds a reference an authenticated connection,
which we don't want to lose.
"""
clone = copy.deepcopy(self)
clone._dataset = self._dataset # Make a shallow copy of the Dataset.
return clone
@classmethod
def from_protobuf(cls, pb, dataset=None):
path = []
for element in pb.path_element:
element_dict = {'kind': element.kind}
if element.HasField('id'):
element_dict['id'] = element.id
elif element.HasField('name'):
element_dict['name'] = element.name
path.append(element_dict)
if not dataset:
dataset = Dataset(id=pb.partition_id.dataset_id)
return cls(path=path, dataset=dataset)
def to_protobuf(self):
key = datastore_pb.Key()
# Technically a dataset is required to do anything with the key,
# but we shouldn't throw a cryptic error if one isn't provided
# in the initializer.
if self.dataset():
# Apparently 's~' is a prefix for High-Replication and is necessary here.
# Another valid preflix is 'e~' indicating EU datacenters.
dataset_id = self.dataset().id()
if dataset_id:
if dataset_id[:2] not in ['s~', 'e~']:
dataset_id = 's~' + dataset_id
key.partition_id.dataset_id = dataset_id
if self._namespace:
key.partition_id.namespace = self._namespace
for item in self.path():
element = key.path_element.add()
if 'kind' in item:
element.kind = item['kind']
if 'id' in item:
element.id = item['id']
if 'name' in item:
element.name = item['name']
return key
@classmethod
def from_path(cls, *args, **kwargs):
path = []
items = iter(args)
for kind, id_or_name in izip(items, items):
entry = {'kind': kind}
if isinstance(id_or_name, basestring):
entry['name'] = id_or_name
else:
entry['id'] = id_or_name
path.append(entry)
kwargs['path'] = path
return cls(**kwargs)
def is_partial(self):
return (self.id_or_name() is None)
def dataset(self, dataset=None):
if dataset:
clone = self._clone()
clone._dataset = dataset
return clone
else:
return self._dataset
def namespace(self, namespace=None):
if namespace:
clone = self._clone()
clone._namespace = namespace
return clone
else:
return self._namespace
def path(self, path=None):
if path:
clone = self._clone()
clone._path = path
return clone
else:
return self._path
def kind(self, kind=None):
if kind:
clone = self._clone()
clone._path[-1]['kind'] = kind
return clone
elif self.path():
return self._path[-1]['kind']
def id(self, id=None):
if id:
clone = self._clone()
clone._path[-1]['id'] = id
return clone
elif self.path():
return self._path[-1].get('id')
def name(self, name=None):
if name:
clone = self._clone()
clone._path[-1]['name'] = name
return clone
elif self.path():
return self._path[-1].get('name')
def id_or_name(self):
return self.id() or self.name()
def parent(self):#pragma NO COVER
# See https://github.com/GoogleCloudPlatform/gcloud-python/issues/135
raise NotImplementedError
def __repr__(self): #pragma NO COVER
return '<Key%s>' % self.path()