Revision a182a3ed lib/serializer.py

b/lib/serializer.py
42 42
from ganeti import utils
43 43

  
44 44

  
45
_JSON_INDENT = 2
46

  
47 45
_RE_EOLSP = re.compile("[ \t]+$", re.MULTILINE)
48 46

  
49 47

  
50
def _GetJsonDumpers(_encoder_class=simplejson.JSONEncoder):
51
  """Returns two JSON functions to serialize data.
52

  
53
  @rtype: (callable, callable)
54
  @return: The function to generate a compact form of JSON and another one to
55
           generate a more readable, indented form of JSON (if supported)
56

  
57
  """
58
  plain_encoder = _encoder_class(sort_keys=True)
59

  
60
  # Check whether the simplejson module supports indentation
61
  try:
62
    indent_encoder = _encoder_class(indent=_JSON_INDENT, sort_keys=True)
63
  except TypeError:
64
    # Indentation not supported
65
    indent_encoder = plain_encoder
66

  
67
  return (plain_encoder.encode, indent_encoder.encode)
68

  
69

  
70
(_DumpJson, _DumpJsonIndent) = _GetJsonDumpers()
71

  
72

  
73
def DumpJson(data, indent=True):
48
def DumpJson(data):
74 49
  """Serialize a given object.
75 50

  
76 51
  @param data: the data to serialize
77
  @param indent: whether to indent output (depends on simplejson version)
78

  
79 52
  @return: the string representation of data
80 53

  
81 54
  """
82
  if indent:
83
    fn = _DumpJsonIndent
84
  else:
85
    fn = _DumpJson
55
  encoded = simplejson.dumps(data)
86 56

  
87
  txt = _RE_EOLSP.sub("", fn(data))
57
  txt = _RE_EOLSP.sub("", encoded)
88 58
  if not txt.endswith("\n"):
89 59
    txt += "\n"
90 60

  
......
112 82
  @return: the string representation of data signed by the hmac key
113 83

  
114 84
  """
115
  txt = DumpJson(data, indent=False)
85
  txt = DumpJson(data)
116 86
  if salt is None:
117 87
    salt = ""
118 88
  signed_dict = {
......
127 97

  
128 98
  signed_dict["hmac"] = utils.Sha1Hmac(key, txt, salt=salt + key_selector)
129 99

  
130
  return DumpJson(signed_dict, indent=False)
100
  return DumpJson(signed_dict)
131 101

  
132 102

  
133 103
def LoadSignedJson(txt, key):

Also available in: Unified diff