This repository has been archived by the owner on Feb 9, 2022. It is now read-only.
forked from ricardokirkner/collection-json.python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collection_json.py
541 lines (426 loc) · 16.4 KB
/
collection_json.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
"""Classes for representing a Collection+JSON document."""
from __future__ import absolute_import, unicode_literals
import json
__version__ = '0.1.1'
class ArrayProperty(object):
"""A descriptor that converts from any enumerable to a typed Array."""
def __init__(self, cls, name):
"""Constructs typed array property
:param cls type: the type of objects expected in the array
:param name str: name of the property
"""
self.cls = cls
self.name = name
def __get__(self, instance, owner):
target = instance
if target is None:
target = owner
if self.name in target.__dict__:
return target.__dict__[self.name]
raise AttributeError
def __set__(self, instance, value):
if value is None:
value = []
instance.__dict__[self.name] = Array(self.cls, self.name, value)
class DictProperty(object):
"""A descriptor that converts to a dictionary containing Arrays or objects of a given type"""
def __init__(self, cls, name):
"""Constructs the dictionary
:param cls type: the expected type of the objects
"""
self.cls = cls
self.name = name
def __get__(self, instance, owner):
target = instance
if target is None:
target = owner
if self.name in target.__dict__:
return target.__dict__[self.name]
raise AttributeError
def __set__(self, instance, vals):
instance.__dict__[self.name] = {}
if vals is not None:
for name, value in vals.items():
if value is None or isinstance(value, self.cls):
instance.__dict__[self.name][name] = value
elif isinstance(value, dict):
instance.__dict__[self.name][name] = self.cls(**value)
elif isinstance(value, list):
self.cls = self.cls
instance.__dict__[self.name][name] = Array(self.cls, None, value)
else:
raise TypeError("Invalid value '%s', "
"expected dict, list or '%s'" % (value,
self.cls.__name__))
class TypedProperty(object):
"""A descriptor for assigning only a specific type of instance.
Additionally supports assigning a dictionary convertable to the type.
"""
def __init__(self, cls, name):
"""Constructs the typed property
:param cls type: the type of object expected
"""
self.cls = cls
self.name = name
def __get__(self, instance, owner):
target = instance
if target is None:
target = owner
if self.name in target.__dict__:
return target.__dict__[self.name]
raise AttributeError
def __set__(self, instance, value):
if value is None or isinstance(value, self.cls):
instance.__dict__[self.name] = value
elif isinstance(value, dict):
instance.__dict__[self.name] = self.cls(**value)
else:
raise TypeError("Invalid value '%s', "
"expected dict or '%s'" % (value,
self.cls.__name__))
class ComparableObject(object):
"""Abstract base class for objects implementing equality comparison.
This class provides default __eq__ and __ne__ implementations.
"""
def __eq__(self, other):
"""Return True if both instances are equivalent."""
return (type(self) == type(other) and
self.__dict__ == other.__dict__)
def __ne__(self, other):
"""Return True if both instances are not equivalent."""
return (type(self) != type(other) or
self.__dict__ != other.__dict__)
class Data(ComparableObject):
"""Object representing a Collection+JSON data object."""
def __init__(self, name, value=None, prompt=None, array=None, object=None):
self.name = name
self.value = value
self.array = array
self.object = object
self.prompt = prompt
property_count = 0
if value is not None: property_count = property_count+1
if array is not None: property_count = property_count+1
if object is not None: property_count = property_count+1
if property_count > 1:
raise ValueError('Data can only have one of the three properties.')
def __repr__(self):
data = "name='%s'" % self.name
if self.prompt is not None:
data += " prompt='%s'" % self.prompt
return "<Data: %s>" % data
def to_dict(self):
"""Return a dictionary representing a Data object."""
output = {
'name': self.name
}
if self.value is not None:
output['value'] = self.value
elif self.array is not None:
output['array'] = self.array
elif self.object is not None:
output['object'] = self.object
if self.prompt is not None:
output['prompt'] = self.prompt
return output
class Link(ComparableObject):
"""Object representing a Collection+JSON link object."""
def __init__(self, href, rel, name=None, render=None, prompt=None,
length=None, inline=None):
self.href = href
self.rel = rel
self.name = name
self.render = render
self.prompt = prompt
self.length = length
self.inline = inline
def __repr__(self):
data = "rel='%s'" % self.rel
if self.name:
data += " name='%s'" % self.name
if self.render:
data += " render='%s'" % self.render
if self.prompt:
data += " prompt='%s'" % self.prompt
if self.length:
data += " length='%s'" % self.length
if self.inline:
data += " inline='%s'" % self.inline
return "<Link: %s>" % data
def to_dict(self):
"""Return a dictionary representing a Link object."""
output = {
'href': self.href,
'rel': self.rel,
}
if self.name is not None:
output['name'] = self.name
if self.render is not None:
output['render'] = self.render
if self.prompt is not None:
output['prompt'] = self.prompt
if self.length is not None:
output['length'] = self.length
if self.inline is not None:
output['inline'] = self.inline
return output
class Error(ComparableObject):
"""Object representing a Collection+JSON error object."""
def __init__(self, code=None, message=None, title=None):
self.code = code
self.message = message
self.title = title
def __repr__(self):
data = ''
if self.code is not None:
data += " code='%s'" % self.code
if self.message is not None:
data += " message='%s'" % self.message
if self.title is not None:
data += " title='%s'" % self.title
return "<Error%s>" % data
def to_dict(self):
"""Return a dictionary representing the Error instance."""
output = {}
if self.code:
output['code'] = self.code
if self.message:
output['message'] = self.message
if self.title:
output['title'] = self.title
return output
class Template(ComparableObject):
"""Object representing a Collection+JSON template object."""
data = ArrayProperty(Data, "data")
@staticmethod
def from_json(data):
"""Return a template instance.
Convenience method for parsing 'write' responses,
which should only contain a template object.
This method parses a json string into a Template object.
Raises `ValueError` when no valid document is provided.
"""
try:
data = json.loads(data)
kwargs = data.get('template')
if not kwargs:
raise ValueError
except ValueError:
raise ValueError('Not valid Collection+JSON template data.')
template = Template(**kwargs)
return template
def __init__(self, data=None):
self.data = data
def __repr__(self):
data = [str(item.name) for item in self.data]
return "<Template: data=%s>" % data
def __getattr__(self, name):
return getattr(self.data, name)
@property
def properties(self):
"""Return a list of names that can be looked up on the template."""
return [item.name for item in self.data]
def to_dict(self):
"""Return a dictionary representing a Template object."""
return {
'template': self.data.to_dict()
}
class Array(ComparableObject, list):
"""Object representing a Collection+JSON array."""
def __init__(self, item_class, collection_name, items):
self.item_class = item_class
self.collection_name = collection_name
super(Array, self).__init__(self._build_items(items))
def _build_items(self, items):
result = []
for item in items:
if isinstance(item, self.item_class):
result.append(item)
elif isinstance(item, dict):
result.append(self.item_class(**item))
else:
raise ValueError("Invalid value for %s: %r" % (
self.item_class.__name__, item))
return result
def __eq__(self, other):
"""Return True if both instances are equivalent."""
return (super(Array, self).__eq__(other) and
list.__eq__(self, other))
def __ne__(self, other):
"""Return True if both instances are not equivalent."""
return (super(Array, self).__ne__(other) or
list.__ne__(self, other))
def __getattr__(self, name):
results = self.find(name=name)
if not results:
raise AttributeError
elif len(results) == 1:
results = results[0]
return results
def _matches(self, name=None, rel=None):
for item in self:
item_name = getattr(item, 'name', None)
item_rel = getattr(item, 'rel', None)
if name is not None and item_name == name and rel is None:
# only searching by name
yield item
elif rel is not None and item_rel == rel and name is None:
# only searching by rel
yield item
elif item_name == name and item_rel == rel:
# searching by name and rel
yield item
def find(self, name=None, rel=None):
"""Return a list of items in the array matching name and/or rel.
If both name and rel parameters are provided, returned items must match
both properties.
"""
return list(self._matches(name=name, rel=rel))
def get(self, name=None, rel=None):
"""Return the first item in the array matching name and/or rel.
If both name and rel parameters are provided, the returned item must
match both properties.
If no item is found, raises ValueError.
"""
try:
return next(self._matches(name=name, rel=rel))
except StopIteration:
raise ValueError('No matching item found.')
def to_dict(self):
"""Return a dictionary representing an Array object."""
if self.item_class is Collection:
data = {
item.href: item.to_dict() for item in self
}
else:
data = [
item.to_dict() for item in self
]
if self.collection_name is not None:
return {
self.collection_name: data
}
return data
class Item(ComparableObject):
"""Object representing a Collection+JSON item object."""
data = ArrayProperty(Data, "data")
links = ArrayProperty(Link, "links")
def __init__(self, href=None, data=None, links=None):
self.href = href
self.data = data
self.links = links
def __repr__(self):
return "<Item: href='%s'>" % self.href
def __getattr__(self, name):
return getattr(self.data, name)
@property
def properties(self):
"""Return a list of names that can be looked up on the item."""
return [item.name for item in self.data]
def to_dict(self):
"""Return a dictionary representing an Item object."""
output = {}
if self.href:
output['href'] = self.href
if self.data:
output.update(self.data.to_dict())
if self.links:
output.update(self.links.to_dict())
return output
class Query(ComparableObject):
"""Object representing a Collection+JSON query object."""
data = ArrayProperty(Data, "data")
def __init__(self, href, rel, name=None, prompt=None, data=None):
self.href = href
self.rel = rel
self.name = name
self.prompt = prompt
self.data = data
def __repr__(self):
data = "rel='%s'" % self.rel
if self.name:
data += " name='%s'" % self.name
if self.prompt:
data += " prompt='%s'" % self.prompt
return "<Query: %s>" % data
def to_dict(self):
"""Return a dictionary representing a Query object."""
output = {
'href': self.href,
'rel': self.rel,
}
if self.name is not None:
output['name'] = self.name
if self.prompt is not None:
output['prompt'] = self.prompt
if len(self.data):
output.update(self.data.to_dict())
return output
class Collection(ComparableObject):
"""Object representing a Collection+JSON document."""
@staticmethod
def from_json(data):
"""Return a Collection instance.
This method parses a json string into a Collection object.
Raises `ValueError` when no valid document is provided.
"""
try:
data = json.loads(data)
kwargs = data.get('collection')
if not kwargs:
raise ValueError
if 'inline' in kwargs and kwargs['inline']:
kwargs['inline'] = [Collection(**data.get('collection'))
for data in kwargs['inline'].values()]
except ValueError:
raise ValueError('Not a valid Collection+JSON document.')
collection = Collection(**kwargs)
return collection
def __new__(cls, *args, **kwargs):
cls.error = TypedProperty(Error, 'error')
cls.errors = DictProperty(Error, 'errors')
cls.template = TypedProperty(Template, 'template')
cls.items = ArrayProperty(Item, 'items')
cls.links = ArrayProperty(Link, 'links')
cls.inline = ArrayProperty(Collection, 'inline')
cls.queries = ArrayProperty(Query, 'queries')
return super(Collection, cls).__new__(cls)
def __init__(self, href, links=None, items=None, inline=None, queries=None,
template=None, error=None, errors=None, version='1.0'):
self.version = version
self.href = href
self.error = error
self.errors = errors
self.template = template
self.items = items
self.links = links
self.inline = inline
self.queries = queries
def __repr__(self):
return "<Collection: version='%s' href='%s'>" % (
self.version, self.href)
def __str__(self):
return json.dumps(self.to_dict())
def to_dict(self):
"""Return a dictionary representing a Collection object."""
output = {
'collection': {
'version': self.version,
'href': self.href,
}
}
if self.links:
output['collection'].update(self.links.to_dict())
if self.items:
output['collection'].update(self.items.to_dict())
if self.inline:
output['collection'].update(self.inline.to_dict())
if self.queries:
output['collection'].update(self.queries.to_dict())
if self.template:
output['collection'].update(self.template.to_dict())
if self.error:
output['collection'].update(self.error.to_dict())
if self.errors:
output['collection']['errors'] = {name : value.to_dict() for name, value in self.errors.items()}
return output