Skip to content

Commit ec44467

Browse files
author
Antti Myyrä
committed
Storage upload: Support Binarylike objects
1 parent 5127705 commit ec44467

File tree

1 file changed

+12
-3
lines changed

1 file changed

+12
-3
lines changed

upcloud_api/cloud_manager/storage_mixin.py

Lines changed: 12 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from os import PathLike
2-
from typing import Optional, Union
2+
from typing import BinaryIO, Optional, Union
33

44
from upcloud_api.api import API
55
from upcloud_api.storage import Storage
@@ -198,7 +198,7 @@ def create_storage_import(
198198
def upload_file_for_storage_import(
199199
self,
200200
storage_import: StorageImport,
201-
file: Union[str, PathLike],
201+
file: Union[str, PathLike, BinaryIO],
202202
timeout: int = 30,
203203
content_type: str = 'application/octet-stream',
204204
):
@@ -212,7 +212,13 @@ def upload_file_for_storage_import(
212212
# seem to be a point in adding a `.api.raw_request()` call to the `API` class.
213213
# That could be changed if there starts to be more of these cases.
214214

215-
with open(file, 'rb') as f:
215+
f = file
216+
needs_closing = False
217+
if not hasattr(file, 'read'):
218+
f = open(file, 'rb')
219+
needs_closing = True
220+
221+
try:
216222
resp = requests.put(
217223
url=storage_import.direct_upload_url,
218224
data=f,
@@ -222,6 +228,9 @@ def upload_file_for_storage_import(
222228

223229
resp.raise_for_status()
224230
return resp.json()
231+
finally:
232+
if needs_closing:
233+
f.close()
225234

226235
def get_storage_import_details(self, storage: str) -> StorageImport:
227236
"""

0 commit comments

Comments
 (0)