def write_file(path, data, codec=IdentityCodec(), as_root=False, encode=True): """Write data into file using a given codec. Overwrite any existing contents. The written file can be read back into its original form by 'read_file'. :param path Path to the written config file. :type path string :param data: An object representing the file contents. :type data: object :param codec: A codec used to transform the data. :type codec: StreamCodec :param as_root: Execute as root. :type as_root: boolean :param encode: Should the codec encode the data. :type encode: boolean :raises: :class:`UnprocessableEntity` if path not given. """ if path: if as_root: _write_file_as_root(path, data, codec, encode=encode) else: with open(path, 'w') as fp: if encode: fp.write(codec.serialize(data)) else: fp.write(codec.deserialize(data)) fp.flush() else: raise exception.UnprocessableEntity(_("Invalid path: %s") % path)
def read_file(path, codec=IdentityCodec(), as_root=False, decode=True): """ Read a file into a Python data structure digestible by 'write_file'. :param path: Path to the read config file. :type path: string :param codec: A codec used to transform the data. :type codec: StreamCodec :param as_root: Execute as root. :type as_root: boolean :param decode: Should the codec decode the data. :type decode: boolean :returns: A dictionary of key-value pairs. :raises: :class:`UnprocessableEntity` if file doesn't exist. :raises: :class:`UnprocessableEntity` if codec not given. """ if path and exists(path, is_directory=False, as_root=as_root): if as_root: return _read_file_as_root(path, codec, decode=decode) with open(path, 'r') as fp: if decode: return codec.deserialize(fp.read()) return codec.serialize(fp.read()) raise exception.UnprocessableEntity(_("File does not exist: %s") % path)
def read_file(path, codec=IdentityCodec(), as_root=False): """ Read a file into a Python data structure digestible by 'write_file'. :param path Path to the read config file. :type path string :param codec: A codec used to deserialize the data. :type codec: StreamCodec :returns: A dictionary of key-value pairs. :param as_root: Execute as root. :type as_root: boolean :raises: :class:`UnprocessableEntity` if file doesn't exist. :raises: :class:`UnprocessableEntity` if codec not given. """ if path and os.path.exists(path): if as_root: return _read_file_as_root(path, codec) with open(path, 'r') as fp: return codec.deserialize(fp.read()) raise exception.UnprocessableEntity(_("File does not exist: %s") % path)
def test_identity_file_codec(self): data = ("Lorem Ipsum, Lorem Ipsum\n" "Lorem Ipsum, Lorem Ipsum\n" "Lorem Ipsum, Lorem Ipsum\n") self._test_file_codec(data, IdentityCodec())