Skip to content

Commit e1ae568

Browse files
committed
Add func to download asset to file-like object
1 parent 22c6bdc commit e1ae568

1 file changed

Lines changed: 20 additions & 4 deletions

File tree

metafold/assets.py

Lines changed: 20 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -78,24 +78,40 @@ def get(self, asset_id: str, project_id: Optional[str] = None) -> Asset:
7878
r: Response = self._client.get(url)
7979
return Asset(**r.json())
8080

81-
def download_file(
82-
self, asset_id: str, path: Union[str, PathLike],
81+
def download(
82+
self, asset_id: str, f: IO[bytes],
8383
project_id: Optional[str] = None,
8484
):
8585
"""Download an asset.
8686
8787
Args:
8888
asset_id: ID of asset to download.
89-
path: Path to downloaded file.
89+
f: File-like object open for writing in binary mode.
9090
project_id: Asset project ID.
9191
"""
9292
project_id = self._client.project_id(project_id)
9393
url = f"/projects/{project_id}/assets/{asset_id}"
9494
r: Response = self._client.get(url, params={"download": "true"})
9595
r = requests.get(r.json()["link"], stream=True)
96-
with open(path, "wb") as f:
96+
try:
9797
for chunk in r.iter_content(chunk_size=65536): # 64 KiB
9898
f.write(chunk)
99+
finally:
100+
f.close()
101+
102+
def download_file(
103+
self, asset_id: str, path: Union[str, PathLike],
104+
project_id: Optional[str] = None,
105+
):
106+
"""Download an asset.
107+
108+
Args:
109+
asset_id: ID of asset to download.
110+
path: Path to downloaded file.
111+
project_id: Asset project ID.
112+
"""
113+
with open(path, "wb") as f:
114+
self.download(asset_id, f, project_id)
99115

100116
def create(
101117
self, f: Union[str, bytes, PathLike, IO[bytes]],

0 commit comments

Comments
 (0)