1from __future__ import unicode_literals
2
3import json
4
5from rbtools.api.utils import parse_mimetype
6from rbtools.utils.encoding import force_unicode
7
8
9DECODER_MAP = {}
10
11
12def DefaultDecoder(payload):
13    """Default decoder for API payloads.
14
15    The default decoder is used when a decoder is not found in the
16    DECODER_MAP. This will stick the body of the response into the
17    'data' field.
18    """
19    return {
20        'resource': {
21            'data': payload,
22        },
23    }
24
25
26DEFAULT_DECODER = DefaultDecoder
27
28
29def JsonDecoder(payload):
30    # In Python 3, the payload can be bytes, not str, and json.loads explicitly
31    # requires decoded strings.
32    return json.loads(force_unicode(payload))
33
34
35DECODER_MAP['application/json'] = JsonDecoder
36
37
38def decode_response(payload, mime_type):
39    """Decode a Web API response.
40
41    The body of a Web API response will be decoded into a dictionary,
42    according to the provided mime_type.
43    """
44    mime = parse_mimetype(mime_type)
45
46    format = '%s/%s' % (mime['main_type'], mime['format'])
47
48    if format in DECODER_MAP:
49        decoder = DECODER_MAP[format]
50    else:
51        decoder = DEFAULT_DECODER
52
53    return decoder(payload)
54