11from os import PathLike
2- from typing import Optional , Union
2+ from typing import BinaryIO , Optional , Union
33
44from upcloud_api .api import API
55from 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