~allenap/maas/xxx-a-thon

« back to all changes in this revision

Viewing changes to src/provisioningserver/tags.py

  • Committer: MAAS Lander
  • Author(s): Gavin Panella
  • Date: 2016-02-11 12:25:26 UTC
  • mfrom: (4650.1.1 remove-simplejson)
  • Revision ID: maas_lander-20160211122526-21bdxd2jqitaqjtm
[r=blake-rouse,andreserl][bug=1543828][author=allenap] Remove simplejson as a dependency; use the stdlib's json module instead.

Show diffs side-by-side

added added

removed removed

Lines of Context:
9
9
    'process_node_tags',
10
10
    ]
11
11
 
12
 
 
13
12
from collections import OrderedDict
14
13
from functools import partial
15
14
import http.client
 
15
import json
16
16
import urllib.error
17
17
import urllib.parse
18
18
import urllib.request
22
22
from provisioningserver.logger import get_maas_logger
23
23
from provisioningserver.utils import classify
24
24
from provisioningserver.utils.xpath import try_match_xpath
25
 
import simplejson as json
26
25
 
27
26
 
28
27
maaslog = get_maas_logger("tag_processing")
36
35
DEFAULT_BATCH_SIZE = 100
37
36
 
38
37
 
39
 
# A content-type: function mapping that can decode data of that type.
40
 
decoders = {
41
 
    "application/json": lambda data: json.loads(data),
42
 
    "application/bson": lambda data: bson.BSON(data).decode(),
43
 
}
44
 
 
45
 
 
46
38
def process_response(response):
47
39
    """All responses should be httplib.OK.
48
40
 
49
 
    Additionally, `decoders` will be consulted in an attempt to decode
50
 
    the content. If it can't be decoded it will be returned as bytes.
 
41
    The response should contain a BSON document (content-type
 
42
    application/bson) or a JSON document (content-type application/json). If
 
43
    so, the document will be decoded and the result returned, otherwise the
 
44
    raw binary content will be returned.
51
45
 
52
46
    :param response: The result of MAASClient.get/post/etc.
53
47
    :type response: urllib.request.addinfourl (a file-like object that has a
54
48
        .code attribute.)
 
49
 
55
50
    """
56
51
    if response.code != http.client.OK:
57
52
        text_status = http.client.responses.get(response.code, '<unknown>')
61
56
            response.headers, response.fp)
62
57
    content = response.read()
63
58
    content_type = response.headers.get_content_type()
64
 
    if content_type in decoders:
65
 
        decode = decoders[content_type]
66
 
        return decode(content)
 
59
    if content_type == "application/bson":
 
60
        return bson.BSON(content).decode()
 
61
    elif content_type == "application/json":
 
62
        content_charset = response.headers.get_content_charset()
 
63
        return json.loads(content.decode(
 
64
            "utf-8" if content_charset is None else content_charset))
67
65
    else:
68
66
        return content
69
67