From 6dbda8b2f60a1d8dcfdd7f4443a110ac519dbcad Mon Sep 17 00:00:00 2001 From: Will McGugan Date: Thu, 28 Dec 2017 13:44:23 +0000 Subject: [PATCH] added extract method --- fs/base.py | 28 +++++++++++++++++++++++++++- fs/test.py | 10 ++++++++++ tests/test_ftpfs.py | 1 - 3 files changed, 37 insertions(+), 2 deletions(-) diff --git a/fs/base.py b/fs/base.py index 4672161d..a051428c 100644 --- a/fs/base.py +++ b/fs/base.py @@ -43,7 +43,7 @@ class FS(object): # This is the "standard" meta namespace. _meta = {} - + # most FS will use default walking algorithms walker_class=Walker @@ -404,6 +404,32 @@ def exists(self, path): else: return True + def extract(self, path, file, **options): + """Copies a file from the filesystem to an binary file-like + object. + + This may be more efficient that opening and copying files + manually if the filesystem supplies an optimized method. + + Arguments: + path (str): Path to a resource + file (file-link): A file-like object open for writing in + binary mode. + options: Implementation specific options required to open + the source file. + + Note that the file object ``file`` will *not* be closed by this + method. Take care to close it after this method completes + (ideally with a context manager). + + Example: + >>> with open('starwars.mov', 'wb') as write_file: + ... my_fs.extract('starwars.mov', write_file) + + """ + with self.openbin(path, **options) as read_file: + tools.copy_file_data(read_file, file) + def filterdir(self, path, files=None, diff --git a/fs/test.py b/fs/test.py index 4e3be148..f2fda2b8 100644 --- a/fs/test.py +++ b/fs/test.py @@ -520,6 +520,16 @@ def test_exists(self): self.assertTrue(self.fs.exists('/')) self.assertTrue(self.fs.exists('')) + def test_extract(self): + test_bytes = b'Hello, World' + self.fs.setbytes('hello.bin', test_bytes) + write_file = io.BytesIO() + self.fs.extract('hello.bin', write_file) + self.assertEqual(write_file.getvalue(), test_bytes) + + with self.assertRaises(errors.ResourceNotFound): + self.fs.extract('foo.bin', write_file) + def test_listdir(self): # Check listing directory that doesn't exist with self.assertRaises(errors.ResourceNotFound): diff --git a/tests/test_ftpfs.py b/tests/test_ftpfs.py index 92e43dbd..6a137ae9 100644 --- a/tests/test_ftpfs.py +++ b/tests/test_ftpfs.py @@ -79,7 +79,6 @@ def test_manager(self): with ftp_errors(mem_fs): raise error_perm('999 foo') - class TestFTPFS(FSTestCases, unittest.TestCase): user = 'user'