3
3
"""
4
4
from rest_framework import parsers
5
5
6
- from . import utils , renderers
6
+ from . import utils , renderers , exceptions
7
+
7
8
8
9
class JSONParser (parsers .JSONParser ):
9
10
"""
@@ -29,10 +30,40 @@ def parse(self, stream, media_type=None, parser_context=None):
29
30
"""
30
31
Parses the incoming bytestream as JSON and returns the resulting data
31
32
"""
32
- result = super (JSONParser , self ).parse (stream , media_type = media_type ,
33
- parser_context = parser_context )
33
+ result = super (JSONParser , self ).parse (stream , media_type = media_type , parser_context = parser_context )
34
34
data = result .get ('data' , {})
35
- attributes = data .get ('attributes' )
36
- if attributes :
37
- attributes ['id' ] = data .get ('id' )
38
- return utils .format_keys (attributes , 'underscore' )
35
+
36
+ if data :
37
+ # Check for inconsistencies
38
+ resource_name = utils .get_resource_name (parser_context )
39
+ if data .get ('type' ) != resource_name :
40
+ raise exceptions .Conflict (
41
+ "The resource object's type ({data_type}) is not the type "
42
+ "that constitute the collection represented by the endpoint ({resource_type})." .format (
43
+ data_type = data .get ('type' ),
44
+ resource_type = resource_name
45
+ )
46
+ )
47
+ # Get the ID
48
+ data_id = data .get ('id' )
49
+ # Get the attributes
50
+ attributes = utils .format_keys (data .get ('attributes' ), 'underscore' ) if data .get (
51
+ 'attributes' ) else dict ()
52
+ # Get the relationships
53
+ relationships = utils .format_keys (data .get ('relationships' ), 'underscore' ) if data .get (
54
+ 'relationships' ) else dict ()
55
+
56
+ # Parse the relationships
57
+ parsed_relationships = dict ()
58
+ for field_name , field_data in relationships .items ():
59
+ field_data = field_data .get ('data' )
60
+ if isinstance (field_data , dict ):
61
+ parsed_relationships [field_name ] = field_data .get ('id' )
62
+ elif isinstance (field_data , list ):
63
+ parsed_relationships [field_name ] = list (relation .get ('id' ) for relation in field_data )
64
+
65
+ # Construct the return data
66
+ parsed_data = {'id' : data_id }
67
+ parsed_data .update (attributes )
68
+ parsed_data .update (parsed_relationships )
69
+ return parsed_data
0 commit comments