Skip to content

Commit 3070b5b

Browse files
author
Joel Lee
committed
feat: add upload
1 parent e85d675 commit 3070b5b

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

supabase_py/lib/storage/storage_file_api.py

+34
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ class StorageFileAPI:
1111
"order": "asc",
1212
},
1313
}
14+
DEFAULT_FILE_OPTIONS = {
15+
"cacheControl": "3600",
16+
"contentType": "text/plain;charset=UTF-8",
17+
"upsert": "False",
18+
}
1419

1520
def __init__(self, url: str, headers: dict, bucket_id: str):
1621
"""
@@ -163,5 +168,34 @@ def download(self, path: str):
163168
else:
164169
return response.content
165170

171+
def upload(self, path: str, file: any, file_options: dict = None):
172+
"""
173+
Uploads a file to an existing bucket.
174+
Parameters
175+
----------
176+
path
177+
The relative file path including the bucket ID. Should be of the format `bucket/folder/subfolder/filename.png`. The bucket must already exist before attempting to upload.
178+
file
179+
The File object to be stored in the bucket. or a async generator of chunks
180+
file_options
181+
HTTP headers. For example `cacheControl`
182+
"""
183+
if file_options is None:
184+
file_options = {}
185+
headers = dict(self.headers, **file_options)
186+
headers.update(self.DEFAULT_FILE_OPTIONS)
187+
files = {"file": open(file, "rb")}
188+
_path = self._get_final_path(path)
189+
try:
190+
resp = requests.post(
191+
f"{self.url}/object/{_path}", data=files, headers=headers
192+
)
193+
except HTTPError as http_err:
194+
print(f"HTTP error occurred: {http_err}") # Python 3.6
195+
except Exception as err:
196+
raise err # Python 3.6
197+
else:
198+
return resp
199+
166200
def _get_final_path(self, path: str):
167201
return f"{self.bucket_id}/{path}"

0 commit comments

Comments
 (0)