Repository navigation
Expand file tree
/
Copy pathserializer.py
More file actions
1170 lines (946 loc) · 43.9 KB
/
Copy pathserializer.py
File metadata and controls
1170 lines (946 loc) · 43.9 KB
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
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""
SQLAlchemy-JSONAPI
Serializer
Colton J. Provias
MIT License
"""
try:
from enum import Enum
except ImportError:
from enum34 import Enum
from inflection import dasherize, tableize, underscore
from sqlalchemy.exc import IntegrityError
from sqlalchemy.orm.interfaces import MANYTOONE
from sqlalchemy.util.langhelpers import iterate_attributes
from .errors import (BadRequestError, InvalidTypeForEndpointError,
MissingTypeError, NotSortableError, PermissionDeniedError,
RelationshipNotFoundError, ResourceNotFoundError,
ResourceTypeNotFoundError, ToManyExpectedError,
ValidationError)
from ._version import __version__
class AttributeActions(Enum):
""" The actions that can be done to an attribute. """
GET = 0
SET = 1
class RelationshipActions(Enum):
""" The actions that can be performed on a relationship. """
GET = 10
APPEND = 11
SET = 12
DELETE = 13
class Permissions(Enum):
""" The permissions that can be set. """
VIEW = 100
CREATE = 101
EDIT = 102
DELETE = 103
class MissingKey:
def __init__(self, elem):
self.elem = elem
def __repr__(self):
return '<{} elem={}>'.format(self.__class__.__name__, self.elem)
ALL_PERMISSIONS = {
Permissions.VIEW, Permissions.CREATE, Permissions.EDIT, Permissions.DELETE
}
INTERACTIVE_PERMISSIONS = {
Permissions.CREATE, Permissions.EDIT, Permissions.DELETE
}
def attr_descriptor(action, *names):
"""
Wrap a function that allows for getting or setting of an attribute. This
allows for specific handling of an attribute when it comes to serializing
and deserializing.
:param action: The AttributeActions that this descriptor performs
:param names: A list of names of the attributes this references
"""
if isinstance(action, AttributeActions):
action = [action]
def wrapped(fn):
if not hasattr(fn, '__jsonapi_action__'):
fn.__jsonapi_action__ = set()
fn.__jsonapi_desc_for_attrs__ = set()
fn.__jsonapi_desc_for_attrs__ |= set(names)
fn.__jsonapi_action__ |= set(action)
return fn
return wrapped
def relationship_descriptor(action, *names):
"""
Wrap a function for modification of a relationship. This allows for
specific handling for serialization and deserialization.
:param action: The RelationshipActions that this descriptor performs
:param names: A list of names of the relationships this references
"""
if isinstance(action, RelationshipActions):
action = [action]
def wrapped(fn):
if not hasattr(fn, '__jsonapi_action__'):
fn.__jsonapi_action__ = set()
fn.__jsonapi_desc_for_rels__ = set()
fn.__jsonapi_desc_for_rels__ |= set(names)
fn.__jsonapi_action__ |= set(action)
return fn
return wrapped
class PermissionTest(object):
""" Authorize access to a model, resource, or specific field. """
def __init__(self, permission, *names):
"""
Decorates a function that returns a boolean representing if access is
allowed.
:param permission: The permission to check for
:param names: The names to test for. None represents the model.
"""
if isinstance(permission, Permissions):
self.permission = [permission]
else:
self.permission = permission
self.names = names if len(names) > 0 else [None]
def __call__(self, fn):
"""
Decorate the function for later processing.
:param fn: Function to decorate
"""
if not hasattr(fn, '__jsonapi_chk_perm_for__'):
fn.__jsonapi_check_permission__ = set()
fn.__jsonapi_chk_perm_for__ = set()
fn.__jsonapi_chk_perm_for__ |= set(self.names)
fn.__jsonapi_check_permission__ |= set(self.permission)
return fn
#: More consistent name for the decorators
permission_test = PermissionTest
class JSONAPIResponse(object):
""" Wrapper for JSON API Responses. """
def __init__(self):
""" Default the status code and data. """
self.status_code = 200
self.data = {
'jsonapi': {'version': '1.0'},
'meta': {'sqlalchemy_jsonapi_version': __version__}
}
def get_permission_test(model, field, permission, instance=None):
"""
Fetch a permission test for a field and permission.
:param model: The model or instance
:param field: Name of the field or None for instance/model-wide
:param permission: Permission to check for
"""
return getattr(model, '__jsonapi_permissions__', {})\
.get(field, {})\
.get(permission, lambda x: True)
def check_permission(instance, field, permission):
"""
Check a permission for a given instance or field. Raises an error if
denied.
:param instance: The instance to check
:param field: The field name to check or None for instance
:param permission: The permission to check
"""
if not get_permission_test(instance, field, permission)(instance):
raise PermissionDeniedError(permission, instance, instance, field)
def get_attr_desc(instance, attribute, action):
"""
Fetch the appropriate descriptor for the attribute.
:param instance: Model instance
:param attribute: Name of the attribute
:param action: AttributeAction
"""
descs = instance.__jsonapi_attribute_descriptors__.get(attribute, {})
if action == AttributeActions.GET:
check_permission(instance, attribute, Permissions.VIEW)
return descs.get(action, lambda x: getattr(x, attribute))
check_permission(instance, attribute, Permissions.EDIT)
return descs.get(action, lambda x, v: setattr(x, attribute, v))
def get_rel_desc(instance, key, action):
"""
Fetch the appropriate descriptor for the relationship.
:param instance: Model instance
:param key: Name of the relationship
:param action: RelationshipAction
"""
descs = instance.__jsonapi_rel_desc__.get(key, {})
if action == RelationshipActions.GET:
check_permission(instance, key, Permissions.VIEW)
return descs.get(action, lambda x: getattr(x, key))
elif action == RelationshipActions.APPEND:
check_permission(instance, key, Permissions.CREATE)
return descs.get(action, lambda x, v: getattr(x, key).append(v))
elif action == RelationshipActions.SET:
check_permission(instance, key, Permissions.EDIT)
return descs.get(action, lambda x, v: setattr(x, key, v))
else:
check_permission(instance, key, Permissions.DELETE)
return descs.get(action, lambda x, v: getattr(x, key).remove(v))
class JSONAPI(object):
""" JSON API Serializer for SQLAlchemy ORM models. """
def __init__(self, base, prefix=''):
"""
Initialize the serializer.
:param base: Declarative base instance
:param namespace: The namespace of the API endpoint
"""
self.base = base
self.prefix = prefix
self.models = {}
for name, model in base._decl_class_registry.items():
if name.startswith('_'):
continue
prepped_name = self._api_type_for_model(model)
api_type = getattr(
model, '__jsonapi_type_override__', prepped_name)
model_keys = set(model.__mapper__.all_orm_descriptors.keys())
model_keys |= set(model.__mapper__.relationships.keys())
model.__jsonapi_attribute_descriptors__ = {}
model.__jsonapi_rel_desc__ = {}
model.__jsonapi_permissions__ = {}
model.__jsonapi_type__ = api_type
model.__jsonapi_map_to_py__ = {
dasherize(underscore(x)): x for x in model_keys}
model.__jsonapi_map_to_api__ = {
x: dasherize(underscore(x)) for x in model_keys}
for prop_name, prop_value in iterate_attributes(model):
if hasattr(prop_value, '__jsonapi_desc_for_attrs__'):
defaults = {'get': None, 'set': None}
descriptors = model.__jsonapi_attribute_descriptors__
for attribute in prop_value.__jsonapi_desc_for_attrs__:
descriptors.setdefault(attribute, defaults)
attr_desc = descriptors[attribute]
for action in prop_value.__jsonapi_action__:
attr_desc[action] = prop_value
if hasattr(prop_value, '__jsonapi_desc_for_rels__'):
defaults = {
'get': None,
'set': None,
'append': None,
'remove': None
}
rels_desc = model.__jsonapi_rel_desc__
for relationship in prop_value.__jsonapi_desc_for_rels__:
rels_desc.setdefault(relationship, defaults)
rel_desc = rels_desc[relationship]
for action in prop_value.__jsonapi_action__:
rel_desc[action] = prop_value
if hasattr(prop_value, '__jsonapi_check_permission__'):
defaults = {
'view': [],
'create': [],
'edit': [],
'delete': [],
'remove': [],
'append': []
}
perm_obj = model.__jsonapi_permissions__
for check_for in prop_value.__jsonapi_chk_perm_for__:
perm_obj.setdefault(check_for, defaults)
perm_idv = perm_obj[check_for]
check_perms = prop_value.__jsonapi_check_permission__
for check_perm in check_perms:
perm_idv[check_perm] = prop_value
self.models[model.__jsonapi_type__] = model
def _api_type_for_model(self, model):
return dasherize(tableize(model.__name__))
def _fetch_model(self, api_type):
if api_type not in self.models.keys():
raise ResourceTypeNotFoundError(api_type)
return self.models[api_type]
def _lazy_relationship(self, api_type, obj_id, rel_key):
return {
'self': '{}/{}/{}/relationships/{}'.format(
self.prefix, api_type, obj_id, rel_key),
'related': '{}/{}/{}/{}'.format(
self.prefix, api_type, obj_id, rel_key)
}
def _get_relationship(self, resource, rel_key, permission):
if rel_key not in resource.__mapper__.relationships.keys():
raise RelationshipNotFoundError(resource, resource, rel_key)
relationship = resource.__mapper__.relationships[rel_key]
check_permission(resource, relationship.key, permission)
return relationship
def _check_json_data(self, json_data):
"""
Ensure that the request body is both a hash and has a data key.
:param json_data: The json data provided with the request
"""
if not isinstance(json_data, dict):
raise BadRequestError('Request body should be a JSON hash')
if 'data' not in json_data.keys():
raise BadRequestError('Request should contain data key')
def _fetch_resource(self, session, api_type, obj_id, permission):
"""
Fetch a resource by type and id, also doing a permission check.
:param session: SQLAlchemy session
:param api_type: The type
:param obj_id: ID for the resource
:param permission: Permission to check
"""
if api_type not in self.models.keys():
raise ResourceTypeNotFoundError(api_type)
obj = session.query(self.models[api_type]).get(obj_id)
if obj is None:
raise ResourceNotFoundError(self.models[api_type], obj_id)
check_permission(obj, None, permission)
return obj
def _render_short_instance(self, instance):
"""
For those very short versions of resources, we have this.
:param instance: The instance to render
"""
check_permission(instance, None, Permissions.VIEW)
return {'type': instance.__jsonapi_type__, 'id': instance.id}
def _render_full_resource(self, instance, include, fields):
"""
Generate a representation of a full resource to match JSON API spec.
:param instance: The instance to serialize
:param include: Dictionary of relationships to include
:param fields: Dictionary of fields to filter
"""
api_type = instance.__jsonapi_type__
orm_desc_keys = instance.__mapper__.all_orm_descriptors.keys()
to_ret = {
'id': instance.id,
'type': api_type,
'attributes': {},
'relationships': {},
'included': {}
}
attrs_to_ignore = {'__mapper__', 'id'}
if api_type in fields.keys():
local_fields = list(map((
lambda x: instance.__jsonapi_map_to_py__[x]),
fields[api_type]))
else:
local_fields = orm_desc_keys
for key, relationship in instance.__mapper__.relationships.items():
attrs_to_ignore |= set([c.name for c in relationship.local_columns
]) | {key}
api_key = instance.__jsonapi_map_to_api__[key]
try:
desc = get_rel_desc(instance, key, RelationshipActions.GET)
except PermissionDeniedError:
continue
if relationship.direction == MANYTOONE:
if key in local_fields:
to_ret['relationships'][api_key] = {
'links': self._lazy_relationship(api_type, instance.id,
api_key)
}
if api_key in include.keys():
related = desc(instance)
if related is not None:
perm = get_permission_test(
related, None, Permissions.VIEW)
if (key in local_fields
and (related is None or not perm(related))):
to_ret['relationships'][api_key]['data'] = None
continue
if key in local_fields:
to_ret['relationships'][api_key]['data'] = self._render_short_instance(related) # NOQA
new_include = self._parse_include(include[api_key])
built = self._render_full_resource(
related, new_include, fields)
included = built.pop('included')
to_ret['included'].update(included)
to_ret['included'][(related.__jsonapi_type__, related.id)] = built # NOQA
else:
if key in local_fields:
to_ret['relationships'][api_key] = {
'links': self._lazy_relationship(
api_type, instance.id, api_key),
}
if api_key not in include.keys():
continue
if key in local_fields:
to_ret['relationships'][api_key]['data'] = []
related = desc(instance)
for item in related:
try:
check_permission(item, None, Permissions.VIEW)
except PermissionDeniedError:
continue
if key in local_fields:
to_ret['relationships'][api_key]['data'].append(
self._render_short_instance(item))
new_include = self._parse_include(include[api_key])
built = self._render_full_resource(item, new_include,
fields)
included = built.pop('included')
to_ret['included'].update(included)
to_ret['included'][(item.__jsonapi_type__, item.id)] = built # NOQA
for key in set(orm_desc_keys) - attrs_to_ignore:
try:
desc = get_attr_desc(instance, key, AttributeActions.GET)
if key in local_fields:
to_ret['attributes'][instance.__jsonapi_map_to_api__[key]] = desc(instance) # NOQA
except PermissionDeniedError:
continue
return to_ret
def _check_instance_relationships_for_delete(self, instance):
"""
Ensure we are authorized to delete this and all cascaded resources.
:param instance: The instance to check the relationships of.
"""
check_permission(instance, None, Permissions.DELETE)
for rel_key, rel in instance.__mapper__.relationships.items():
check_permission(instance, rel_key, Permissions.EDIT)
if rel.cascade.delete:
if rel.direction == MANYTOONE:
related = getattr(instance, rel_key)
self._check_instance_relationships_for_delete(related)
else:
instances = getattr(instance, rel_key)
for to_check in instances:
self._check_instance_relationships_for_delete(to_check)
def _parse_fields(self, query):
"""
Parse the querystring args for fields.
:param query: Dict of query args
"""
field_args = {
k: v
for k, v in query.items() if k.startswith('fields[')
}
fields = {}
for k, v in field_args.items():
fields[k[7:-1]] = v.split(',')
return fields
def _parse_include(self, include):
"""
Parse the querystring args or parent includes for includes.
:param include: Dict of query args or includes
"""
ret = {}
for item in include:
if '.' in item:
local, remote = item.split('.', 1)
else:
local = item
remote = None
ret.setdefault(local, [])
if remote:
ret[local].append(remote)
return ret
def _parse_page(self, query):
"""
Parse the querystring args for pagination.
:param query: Dict of query args
"""
args = {k[5:-1]: v for k, v in query.items() if k.startswith('page[')}
if {'number', 'size'} == set(args.keys()):
if not args['number'].isdecimal() or not args['size'].isdecimal():
raise BadRequestError('Page query parameters must be integers')
number = int(args['number'])
size = int(args['size'])
start = number * size
return start, start + size - 1
if {'limit', 'offset'} == set(args.keys()):
if not args['limit'].isdecimal() or not args['offset'].isdecimal():
raise BadRequestError('Page query parameters must be integers')
limit = int(args['limit'])
offset = int(args['offset'])
return offset, offset + limit - 1
return 0, None
def delete_relationship(self, session, data, api_type, obj_id, rel_key):
"""
Delete a resource or multiple resources from a to-many relationship.
:param session: SQLAlchemy session
:param data: JSON data provided with the request
:param api_type: Type of the resource
:param obj_id: ID of the resource
:param rel_key: Key of the relationship to fetch
"""
model = self._fetch_model(api_type)
resource = self._fetch_resource(session, api_type, obj_id,
Permissions.EDIT)
relationship = self._get_relationship(resource, rel_key,
Permissions.DELETE)
self._check_json_data(data)
if not isinstance(data['data'], list):
raise ValidationError('Provided data must be an array.')
if relationship.direction == MANYTOONE:
return ToManyExpectedError(model, resource, relationship)
response = JSONAPIResponse()
response.data = {'data': []}
session.add(resource)
remove = get_rel_desc(resource, relationship.key,
RelationshipActions.DELETE)
reverse_side = relationship.back_populates
for item in data['data']:
item = self._fetch_resource(session, item['type'], item['id'],
Permissions.EDIT)
if reverse_side:
reverse_rel = item.__mapper__.relationships[reverse_side]
if reverse_rel.direction == MANYTOONE:
permission = Permissions.EDIT
else:
permission = Permissions.DELETE
check_permission(item, reverse_side, permission)
remove(resource, item)
session.commit()
session.refresh(resource)
get = get_rel_desc(resource, relationship.key, RelationshipActions.GET)
for item in get(resource):
response.data['data'].append(self._render_short_instance(item))
return response
def delete_resource(self, session, data, api_type, obj_id):
"""
Delete a resource.
:param session: SQLAlchemy session
:param data: JSON data provided with the request
:param api_type: Type of the resource
:param obj_id: ID of the resource
"""
resource = self._fetch_resource(session, api_type, obj_id,
Permissions.VIEW)
self._check_instance_relationships_for_delete(resource)
session.delete(resource)
session.commit()
response = JSONAPIResponse()
response.status_code = 204
return response
def get_collection(self, session, query, api_key):
"""
Fetch a collection of resources of a specified type.
:param session: SQLAlchemy session
:param query: Dict of query args
:param api_type: The type of the model
"""
model = self._fetch_model(api_key)
include = self._parse_include(query.get('include', '').split(','))
fields = self._parse_fields(query)
included = {}
sorts = query.get('sort', '').split(',')
order_by = []
collection = session.query(model)
for attr in sorts:
if attr == '':
break
attr_name, is_asc = [attr[1:], False]\
if attr[0] == '-'\
else [attr, True]
if attr_name not in model.__mapper__.all_orm_descriptors.keys()\
or not hasattr(model, attr_name)\
or attr_name in model.__mapper__.relationships.keys():
return NotSortableError(model, attr_name)
attr = getattr(model, attr_name)
if not hasattr(attr, 'asc'):
# pragma: no cover
return NotSortableError(model, attr_name)
check_permission(model, attr_name, Permissions.VIEW)
order_by.append(attr.asc() if is_asc else attr.desc())
if len(order_by) > 0:
collection = collection.order_by(*order_by)
pos = -1
start, end = self._parse_page(query)
response = JSONAPIResponse()
response.data['data'] = []
for instance in collection:
try:
check_permission(instance, None, Permissions.VIEW)
except PermissionDeniedError:
continue
pos += 1
if end is not None and (pos < start or pos > end):
continue
built = self._render_full_resource(instance, include, fields)
included.update(built.pop('included'))
response.data['data'].append(built)
response.data['included'] = list(included.values())
return response
def get_resource(self, session, query, api_type, obj_id):
"""
Fetch a resource.
:param session: SQLAlchemy session
:param query: Dict of query args
:param api_type: Type of the resource
:param obj_id: ID of the resource
"""
resource = self._fetch_resource(session, api_type, obj_id,
Permissions.VIEW)
include = self._parse_include(query.get('include', '').split(','))
fields = self._parse_fields(query)
response = JSONAPIResponse()
built = self._render_full_resource(resource, include, fields)
response.data['included'] = list(built.pop('included').values())
response.data['data'] = built
return response
def get_related(self, session, query, api_type, obj_id, rel_key):
"""
Fetch a collection of related resources.
:param session: SQLAlchemy session
:param query: Dict of query args
:param api_type: Type of the resource
:param obj_id: ID of the resource
:param rel_key: Key of the relationship to fetch
"""
resource = self._fetch_resource(session, api_type, obj_id,
Permissions.VIEW)
if rel_key not in resource.__jsonapi_map_to_py__.keys():
raise RelationshipNotFoundError(resource, resource, rel_key)
py_key = resource.__jsonapi_map_to_py__[rel_key]
relationship = self._get_relationship(resource, py_key,
Permissions.VIEW)
response = JSONAPIResponse()
related = get_rel_desc(resource, relationship.key,
RelationshipActions.GET)(resource)
if relationship.direction == MANYTOONE:
try:
if related is None:
response.data['data'] = None
else:
response.data['data'] = self._render_full_resource(related,
{}, {})
except PermissionDeniedError:
response.data['data'] = None
else:
response.data['data'] = []
for item in related:
try:
response.data['data'].append(
self._render_full_resource(item, {}, {}))
except PermissionDeniedError:
continue
return response
def get_relationship(self, session, query, api_type, obj_id, rel_key):
"""
Fetch a collection of related resource types and ids.
:param session: SQLAlchemy session
:param query: Dict of query args
:param api_type: Type of the resource
:param obj_id: ID of the resource
:param rel_key: Key of the relationship to fetch
"""
resource = self._fetch_resource(session, api_type, obj_id,
Permissions.VIEW)
if rel_key not in resource.__jsonapi_map_to_py__.keys():
raise RelationshipNotFoundError(resource, resource, rel_key)
py_key = resource.__jsonapi_map_to_py__[rel_key]
relationship = self._get_relationship(resource, py_key,
Permissions.VIEW)
response = JSONAPIResponse()
related = get_rel_desc(resource, relationship.key,
RelationshipActions.GET)(resource)
if relationship.direction == MANYTOONE:
if related is None:
response.data['data'] = None
else:
try:
response.data['data'] = self._render_short_instance(
related)
except PermissionDeniedError:
response.data['data'] = None
else:
response.data['data'] = []
for item in related:
try:
response.data['data'].append(
self._render_short_instance(item))
except PermissionDeniedError:
continue
return response
def patch_relationship(self, session, json_data, api_type, obj_id,
rel_key):
"""
Replacement of relationship values.
:param session: SQLAlchemy session
:param json_data: Request JSON Data
:param api_type: Type of the resource
:param obj_id: ID of the resource
:param rel_key: Key of the relationship to fetch
"""
model = self._fetch_model(api_type)
resource = self._fetch_resource(session, api_type, obj_id,
Permissions.EDIT)
if rel_key not in resource.__jsonapi_map_to_py__.keys():
raise RelationshipNotFoundError(resource, resource, rel_key)
py_key = resource.__jsonapi_map_to_py__[rel_key]
relationship = self._get_relationship(resource, py_key,
Permissions.EDIT)
self._check_json_data(json_data)
session.add(resource)
remote_side = relationship.back_populates
try:
if relationship.direction == MANYTOONE:
if not isinstance(json_data['data'], dict)\
and json_data['data'] is not None:
raise ValidationError('Provided data must be a hash.')
related = getattr(resource, relationship.key)
check_permission(related, None, Permissions.EDIT)
check_permission(related, remote_side, Permissions.EDIT)
setter = get_rel_desc(resource, relationship.key,
RelationshipActions.SET)
if json_data['data'] is None:
setter(resource, None)
else:
to_relate = self._fetch_resource(
session, json_data['data']['type'],
json_data['data']['id'], Permissions.EDIT)
check_permission(to_relate, remote_side, Permissions.EDIT)
setter(resource, to_relate)
else:
if not isinstance(json_data['data'], list):
raise ValidationError('Provided data must be an array.')
related = getattr(resource, relationship.key)
remover = get_rel_desc(resource, relationship.key,
RelationshipActions.DELETE)
appender = get_rel_desc(resource, relationship.key,
RelationshipActions.APPEND)
for item in related:
check_permission(item, None, Permissions.EDIT)
remote = item.__mapper__.relationships[remote_side]
if remote.direction == MANYTOONE:
check_permission(item, remote_side, Permissions.EDIT)
else:
check_permission(item, remote_side, Permissions.DELETE)
remover(resource, item)
for item in json_data['data']:
to_relate = self._fetch_resource(
session, item['type'], item['id'], Permissions.EDIT)
remote = to_relate.__mapper__.relationships[remote_side]
if remote.direction == MANYTOONE:
check_permission(to_relate, remote_side,
Permissions.EDIT)
else:
check_permission(to_relate, remote_side,
Permissions.CREATE)
appender(resource, to_relate)
session.commit()
except KeyError:
raise ValidationError('Incompatible Type')
return self.get_relationship(session, {}, model.__jsonapi_type__,
resource.id, rel_key)
def patch_resource(self, session, json_data, api_type, obj_id):
"""
Replacement of resource values.
:param session: SQLAlchemy session
:param json_data: Request JSON Data
:param api_type: Type of the resource
:param obj_id: ID of the resource
"""
model = self._fetch_model(api_type)
resource = self._fetch_resource(session, api_type, obj_id,
Permissions.EDIT)
self._check_json_data(json_data)
orm_desc_keys = resource.__mapper__.all_orm_descriptors.keys()
if not ({'type', 'id'} <= set(json_data['data'].keys())):
raise BadRequestError('Missing type or id')
if str(json_data['data']['id']) != str(resource.id):
raise BadRequestError('IDs do not match')
if json_data['data']['type'] != resource.__jsonapi_type__:
raise BadRequestError('Type does not match')
json_data['data'].setdefault('relationships', {})
json_data['data'].setdefault('attributes', {})
missing_keys = set(json_data['data'].get('relationships', {}).keys()) \
- set(resource.__jsonapi_map_to_py__.keys())
if missing_keys:
raise BadRequestError(
'{} not relationships for {}.{}'.format(
', '.join(list(missing_keys)),
model.__jsonapi_type__, resource.id))
attrs_to_ignore = {'__mapper__', 'id'}
session.add(resource)
try:
for key, relationship in resource.__mapper__.relationships.items():
api_key = resource.__jsonapi_map_to_api__[key]
attrs_to_ignore |= set(relationship.local_columns) | {key}
if api_key not in json_data['data']['relationships'].keys():
continue
self.patch_relationship(
session, json_data['data']['relationships'][api_key],
model.__jsonapi_type__, resource.id, api_key)
data_keys = set(map((
lambda x: resource.__jsonapi_map_to_py__.get(x, None)),
json_data['data']['attributes'].keys()))
model_keys = set(orm_desc_keys) - attrs_to_ignore
if not data_keys <= model_keys:
raise BadRequestError(
'{} not attributes for {}.{}'.format(
', '.join(list(data_keys - model_keys)),
model.__jsonapi_type__, resource.id))
for key in data_keys & model_keys:
setter = get_attr_desc(resource, key, AttributeActions.SET)
setter(resource, json_data['data']['attributes'][resource.__jsonapi_map_to_api__[key]]) # NOQA
session.commit()
except IntegrityError as e:
session.rollback()
raise ValidationError(str(e.orig))
except AssertionError as e:
# pragma: no cover
session.rollback()
raise ValidationError(e.msg)
except TypeError as e:
session.rollback()
raise ValidationError('Incompatible data type')
return self.get_resource(
session, {}, model.__jsonapi_type__, resource.id)
def post_collection(self, session, data, api_type):
"""
Create a new Resource.
:param session: SQLAlchemy session
:param data: Request JSON Data
:param params: Keyword arguments
"""
model = self._fetch_model(api_type)
self._check_json_data(data)
orm_desc_keys = model.__mapper__.all_orm_descriptors.keys()
if 'type' not in data['data'].keys():
raise MissingTypeError()
if data['data']['type'] != model.__jsonapi_type__:
raise InvalidTypeForEndpointError(
model.__jsonapi_type__, data['data']['type'])
resource = model()
check_permission(resource, None, Permissions.CREATE)
data['data'].setdefault('relationships', {})
data['data'].setdefault('attributes', {})
data_keys = set(map((
lambda x: resource.__jsonapi_map_to_py__.get(x, MissingKey(x))),
data['data'].get('relationships', {}).keys()))
model_keys = set(resource.__mapper__.relationships.keys())
if not data_keys <= model_keys:
data_keys = set([key.elem if isinstance(key, MissingKey) else key for key in data_keys])
# pragma: no cover
raise BadRequestError(
'{} not relationships for {}'.format(
', '.join([repr(key) for key in list(data_keys - model_keys)]), model.__jsonapi_type__))
attrs_to_ignore = {'__mapper__', 'id'}