|
7 | 7 | from datetime import datetime |
8 | 8 | import os.path |
9 | 9 | import pkgutil |
| 10 | +import zipfile |
10 | 11 |
|
11 | 12 | from Algorithmia.util import getParentAndBase |
12 | 13 | from Algorithmia.data import DataObject, DataObjectType |
@@ -50,6 +51,23 @@ def getFile(self, as_path=False): |
50 | 51 | else: |
51 | 52 | return open(f.name) |
52 | 53 |
|
| 54 | + def getAsZip(self): |
| 55 | + """Download/decompress file/directory and return path to file/directory. |
| 56 | + |
| 57 | + Expects the `DataFile` object to contain a data API path pointing to a file/directory compressed with a zip-based compression algorithm. |
| 58 | + Either returns the directory or a path to the file, depending on whether a directory or file was zipped. |
| 59 | + """ |
| 60 | + local_file_path = self.getFile(as_path=True) |
| 61 | + directory_path = tempfile.mkdtemp() |
| 62 | + with zipfile.ZipFile(local_file_path, 'r') as ziph: |
| 63 | + ziph.extractall(directory_path) |
| 64 | + if len(ziph.namelist()) > 1: |
| 65 | + output_path = directory_path |
| 66 | + else: |
| 67 | + filename = ziph.namelist()[0] |
| 68 | + output_path = os.path.join(directory_path, filename) |
| 69 | + return output_path |
| 70 | + |
53 | 71 | def getName(self): |
54 | 72 | _, name = getParentAndBase(self.path) |
55 | 73 | return name |
@@ -145,6 +163,24 @@ def putNumpy(self, array): |
145 | 163 | else: |
146 | 164 | raise DataApiError("Attempted to .putNumpy() a file without numpy available, please install numpy.") |
147 | 165 |
|
| 166 | + def putAsZip(self, path): |
| 167 | + """Zip file/directory and upload to data API location defined by `DataFile` object. |
| 168 | + |
| 169 | + Accepts either a single file or a directory containing other files and directories. |
| 170 | + """ |
| 171 | + temp = tempfile.NamedTemporaryFile(delete=False).name |
| 172 | + if os.path.isdir(path): |
| 173 | + with zipfile.ZipFile(temp, 'w') as ziph: |
| 174 | + for root, dirs, files in os.walk(path): |
| 175 | + for file in files: |
| 176 | + f_path = os.path.join(root, file) |
| 177 | + arc_path = os.path.relpath(os.path.join(root, file), path) |
| 178 | + ziph.write(f_path, arc_path) |
| 179 | + else: |
| 180 | + with zipfile.ZipFile(temp, 'w') as ziph: |
| 181 | + ziph.write(path) |
| 182 | + return self.putFile(temp) |
| 183 | + |
148 | 184 | def delete(self): |
149 | 185 | # Delete from data api |
150 | 186 | result = self.client.deleteHelper(self.url) |
@@ -256,7 +292,7 @@ def __del__(self): |
256 | 292 | filepath = self.local_file.name |
257 | 293 | self.local_file.close() |
258 | 294 | if self.cleanup: |
259 | | - os.remove(filepath) |
| 295 | + os.remove(filepath) |
260 | 296 |
|
261 | 297 | def readable(self): |
262 | 298 | return True |
|
0 commit comments