Example #1
0
    def _loadjson(self, fname, dest):
        """Load JSON file located under self._directory, if needed

        :param fname: short file name (without path and .json)
        :type fname: str.
        :param dest: destination
        :type dest: dict
        """
        try:
            fname = "%s/%s.json" % (self._directory, fname)
            mtime = os.stat(fname).st_mtime

            if self._mtimes.get(fname, 0) == mtime:
                # no need to reload the file: the mtime has not been changed
                return

            with open(fname) as f:
                json_data = f.read()
        except Exception as e:
            raise BackendIOException("Unable to read json file %s: %s" % (fname, e))

        try:
            json_obj = json.loads(json_data)
            dest.clear()
            dest.update(json_obj)
            self._mtimes[fname] = os.stat(fname).st_mtime
        except Exception as e:
            raise BackendIOException("Unable to parse JSON data from %s: %s" \
                % (fname, e))
Example #2
0
 def _savejson(self, fname, obj):
     """Save obj in JSON format in a file in self._directory"""
     fname = "%s/%s.json" % (self._directory, fname)
     try:
         s = json.dumps(obj)
         with open("%s.tmp" % fname, 'wb') as f:
             f.write(s)
             f.flush()
         shutil.move("%s.tmp" % fname, fname)
     except Exception as e:
         raise BackendIOException("Unable to save JSON file %s: %s" \
             % (fname, e))