示例#1
0
    def _secure_write(self, f_name, data, serialize=True):
        f_handle = None
        f_name_tmp = os.path.join(self.base_dir, helper.random_str(20, "tmp"))

        try:
            if os.path.exists(f_name):
                shutil.copy2(f_name, f_name_tmp)
            f_handle = open(f_name, "wb")

            if serialize:
                pickle.dump(data, f_handle)
            else:
                f_handle.write(data)

        except Exception as e:
            if f_handle is not None and not f_handle.closed:
                f_handle.close()
            if os.path.exists(f_name_tmp):
                if os.path.exists(f_name):
                    os.remove(f_name)
                os.rename(f_name_tmp, f_name)
            raise e

        else:
            f_handle.close()
            if os.path.exists(f_name_tmp):
                os.remove(f_name_tmp)
示例#2
0
    def _secure_read(self, f_name, default=None, serialize=True):
        f_handle = None
        f_name_tmp = os.path.join(self.base_dir, helper.random_str(20, "tmp"))

        try:
            if os.path.exists(f_name):
                shutil.copy2(f_name, f_name_tmp)
                f_handle = open(f_name, "rb")

                if serialize:
                    try:
                        data = pickle.load(f_handle)
                    except EOFError:
                        data = default
                else:
                    data = f_handle.read()

            else:
                data = default

        except Exception as e:
            if f_handle is not None and not f_handle.closed:
                f_handle.close()
            if os.path.exists(f_name_tmp):
                if os.path.exists(f_name):
                    os.remove(f_name)
                os.rename(f_name_tmp, f_name)
            raise e

        else:
            if f_handle is not None and not f_handle.closed:
                f_handle.close()
            if os.path.exists(f_name_tmp):
                os.remove(f_name_tmp)

        return data