示例#1
0
    def _flatten_dictionary(self, params, parent=None):
        """
            Flatten a hierarchical dictionary into a simple dictionary.

                >>> self._flatten_dictionary({
                    "test": {
                        "foo": 12,
                        "bar": "hello",
                    },
                    "baz": False
                })
                {
                    "test[foo]": 12,
                    "test[bar]": hello,
                    "baz": False
                }
                
        """
        data = OrderedDict()
        for key, val in params.items():
            full_key = parent + "[" + key + "]" if parent else key
            if isinstance(val, dict):
                data.update(self._flatten_dictionary(val, full_key))
            else:
                data[full_key] = val
        return data
示例#2
0
 def _flatten_errors(self, params, parent=None):
     """
         A modified version of the flatten_dictionary method above used
         to coerce the structure holding errors returned by Braintree into
         a flattened dictionary where the keys are the names of the fields
         and the values the error messages, which can be directly used to
         set the field errors on the Django form object for display in
         templates.
     """
     data = OrderedDict()
     for key, val in params.items():
         full_key = parent + "[" + key + "]" if parent else key
         if full_key.endswith("[errors]"):
             full_key = full_key[:-len("[errors]")]
         if isinstance(val, dict):
             data.update(self._flatten_errors(val, full_key))
         elif key == "errors":
             for error in val:
                 data[full_key + "[" + error["attribute"] + "]"] = [error["message"]]
         else:
             data[full_key] = [val]
     return data