示例#1
0
    def dump(data, filepath):
        '''
        Write data as as type self.ext to filepath. json or msgpack
        '''
        if ' ' in filepath:
            raise raeting.KeepError("Invalid filepath '{0}' "
                                    "contains space".format(filepath))

        if hasattr(data, 'get'):
            for key, val in data.items():  # P3 json.dump no encoding parameter
                if isinstance(val, (bytes, bytearray)):
                    data[key] = val.decode('utf-8')

        root, ext = os.path.splitext(filepath)
        if ext == '.json':
            with ocfn(filepath, "w+") as f:
                json.dump(data, f, indent=2)
                f.flush()
                os.fsync(f.fileno())
        elif ext == '.msgpack':
            if not msgpack:
                raise raeting.KeepError("Invalid filepath ext '{0}' "
                            "needs msgpack installed".format(filepath))
            with ocfn(filepath, "w+b", binary=True) as f:
                msgpack.dump(data, f, encoding='utf-8')
                f.flush()
                os.fsync(f.fileno())
        else:
            raise raeting.KeepError("Invalid filepath ext '{0}' "
                        "not '.json' or '.msgpack'".format(filepath))
示例#2
0
    def load(filepath):
        '''
        Return data read from filepath as converted json
        Otherwise return None
        '''

        try:
            root, ext = os.path.splitext(filepath)
            if ext == '.json':
                with ocfn(filepath, "r") as f:
                    it = json.load(f, object_pairs_hook=odict)
            elif ext == '.msgpack':
                if not msgpack:
                    raise raeting.KeepError("Invalid filepath ext '{0}' "
                                "needs msgpack installed".format(filepath))
                with ocfn(filepath, "rb", binary=True) as f:
                    it = msgpack.load(f, object_pairs_hook=odict, encoding='utf-8')
            else:
                it = None
        except EOFError:
            return None
        except ValueError:
            return None
        return it