corebase 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- corebase/__init__.py +108 -0
- corebase/_async/__init__.py +1 -0
- corebase/_async/auth_client.py +55 -0
- corebase/_async/client.py +398 -0
- corebase/_sync/__init__.py +1 -0
- corebase/_sync/auth_client.py +55 -0
- corebase/_sync/client.py +393 -0
- corebase/auth/__init__.py +20 -0
- corebase/auth/_async/__init__.py +1 -0
- corebase/auth/_async/gotrue_admin_api.py +356 -0
- corebase/auth/_async/gotrue_admin_mfa_api.py +32 -0
- corebase/auth/_async/gotrue_admin_oauth_api.py +93 -0
- corebase/auth/_async/gotrue_base_api.py +78 -0
- corebase/auth/_async/gotrue_client.py +1404 -0
- corebase/auth/_async/gotrue_mfa_api.py +94 -0
- corebase/auth/_async/storage.py +31 -0
- corebase/auth/_sync/__init__.py +1 -0
- corebase/auth/_sync/gotrue_admin_api.py +356 -0
- corebase/auth/_sync/gotrue_admin_mfa_api.py +32 -0
- corebase/auth/_sync/gotrue_admin_oauth_api.py +93 -0
- corebase/auth/_sync/gotrue_base_api.py +78 -0
- corebase/auth/_sync/gotrue_client.py +1394 -0
- corebase/auth/_sync/gotrue_mfa_api.py +94 -0
- corebase/auth/_sync/storage.py +31 -0
- corebase/auth/constants.py +15 -0
- corebase/auth/errors.py +259 -0
- corebase/auth/helpers.py +288 -0
- corebase/auth/py.typed +0 -0
- corebase/auth/timer.py +53 -0
- corebase/auth/types.py +1021 -0
- corebase/auth/version.py +1 -0
- corebase/client.py +12 -0
- corebase/functions/__init__.py +47 -0
- corebase/functions/_async/__init__.py +1 -0
- corebase/functions/_async/functions_client.py +218 -0
- corebase/functions/_sync/__init__.py +1 -0
- corebase/functions/_sync/functions_client.py +218 -0
- corebase/functions/errors.py +62 -0
- corebase/functions/py.typed +0 -0
- corebase/functions/utils.py +33 -0
- corebase/functions/version.py +1 -0
- corebase/lib/__init__.py +3 -0
- corebase/lib/client_options.py +189 -0
- corebase/migrate/__init__.py +374 -0
- corebase/migrate/__main__.py +7 -0
- corebase/postgrest/__init__.py +62 -0
- corebase/postgrest/_async/__init__.py +1 -0
- corebase/postgrest/_async/client.py +206 -0
- corebase/postgrest/_async/request_builder.py +503 -0
- corebase/postgrest/_sync/__init__.py +1 -0
- corebase/postgrest/_sync/client.py +206 -0
- corebase/postgrest/_sync/request_builder.py +503 -0
- corebase/postgrest/base_client.py +61 -0
- corebase/postgrest/base_request_builder.py +787 -0
- corebase/postgrest/constants.py +6 -0
- corebase/postgrest/exceptions.py +115 -0
- corebase/postgrest/py.typed +0 -0
- corebase/postgrest/types.py +72 -0
- corebase/postgrest/utils.py +91 -0
- corebase/postgrest/version.py +1 -0
- corebase/py.typed +0 -0
- corebase/realtime/__init__.py +17 -0
- corebase/realtime/_async/__init__.py +0 -0
- corebase/realtime/_async/channel.py +766 -0
- corebase/realtime/_async/client.py +498 -0
- corebase/realtime/_async/presence.py +185 -0
- corebase/realtime/_async/push.py +162 -0
- corebase/realtime/_async/timer.py +41 -0
- corebase/realtime/_sync/__init__.py +0 -0
- corebase/realtime/_sync/channel.py +30 -0
- corebase/realtime/_sync/client.py +71 -0
- corebase/realtime/_sync/presence.py +10 -0
- corebase/realtime/exceptions.py +38 -0
- corebase/realtime/message.py +176 -0
- corebase/realtime/py.typed +0 -0
- corebase/realtime/transformers.py +9 -0
- corebase/realtime/types.py +246 -0
- corebase/realtime/utils.py +5 -0
- corebase/realtime/version.py +1 -0
- corebase/storage/__init__.py +56 -0
- corebase/storage/_async/__init__.py +1 -0
- corebase/storage/_async/analytics.py +82 -0
- corebase/storage/_async/bucket.py +142 -0
- corebase/storage/_async/client.py +106 -0
- corebase/storage/_async/file_api.py +630 -0
- corebase/storage/_async/request.py +32 -0
- corebase/storage/_async/vectors.py +213 -0
- corebase/storage/_sync/__init__.py +1 -0
- corebase/storage/_sync/analytics.py +80 -0
- corebase/storage/_sync/bucket.py +142 -0
- corebase/storage/_sync/client.py +106 -0
- corebase/storage/_sync/file_api.py +630 -0
- corebase/storage/_sync/request.py +32 -0
- corebase/storage/_sync/vectors.py +199 -0
- corebase/storage/constants.py +16 -0
- corebase/storage/exceptions.py +84 -0
- corebase/storage/py.typed +0 -0
- corebase/storage/types.py +313 -0
- corebase/storage/utils.py +26 -0
- corebase/storage/version.py +1 -0
- corebase/types.py +8 -0
- corebase/version.py +1 -0
- corebase-1.0.0.dist-info/METADATA +78 -0
- corebase-1.0.0.dist-info/RECORD +106 -0
- corebase-1.0.0.dist-info/WHEEL +4 -0
- corebase-1.0.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,630 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import builtins
|
|
4
|
+
import json
|
|
5
|
+
import urllib.parse
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from io import BufferedReader, FileIO
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any, Literal, cast
|
|
10
|
+
|
|
11
|
+
from httpx import AsyncClient, Headers, HTTPStatusError, Response
|
|
12
|
+
from yarl import URL
|
|
13
|
+
|
|
14
|
+
from ..constants import DEFAULT_FILE_OPTIONS, DEFAULT_SEARCH_OPTIONS, DEFAULT_SORT_BY
|
|
15
|
+
from ..exceptions import StorageApiError
|
|
16
|
+
from ..types import (
|
|
17
|
+
BaseBucket,
|
|
18
|
+
CreateSignedUploadUrlOptions,
|
|
19
|
+
CreateSignedUrlResponse,
|
|
20
|
+
CreateSignedURLsOptions,
|
|
21
|
+
DownloadOptions,
|
|
22
|
+
FileOptions,
|
|
23
|
+
ListBucketFilesOptions,
|
|
24
|
+
RequestMethod,
|
|
25
|
+
SearchV2Options,
|
|
26
|
+
SearchV2Result,
|
|
27
|
+
SignedUploadURL,
|
|
28
|
+
SignedUrlJsonResponse,
|
|
29
|
+
SignedUrlResponse,
|
|
30
|
+
SignedUrlsJsonResponse,
|
|
31
|
+
TransformOptions,
|
|
32
|
+
UploadData,
|
|
33
|
+
UploadResponse,
|
|
34
|
+
UploadSignedUrlFileOptions,
|
|
35
|
+
URLOptions,
|
|
36
|
+
transform_to_dict,
|
|
37
|
+
)
|
|
38
|
+
from ..utils import StorageException
|
|
39
|
+
|
|
40
|
+
__all__ = ["AsyncBucket"]
|
|
41
|
+
|
|
42
|
+
|
|
43
|
+
def relative_path_to_parts(path: str) -> tuple[str, ...]:
|
|
44
|
+
parts = urllib.parse.unquote(path, errors="strict").lstrip("/").split("/")
|
|
45
|
+
if "." in parts or ".." in parts:
|
|
46
|
+
raise ValueError(f"Object keys must not contain dot segments: {path!r}")
|
|
47
|
+
return tuple(parts)
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class AsyncBucketActionsMixin:
|
|
51
|
+
"""Functions needed to access the file API."""
|
|
52
|
+
|
|
53
|
+
id: str
|
|
54
|
+
_base_url: URL
|
|
55
|
+
_client: AsyncClient
|
|
56
|
+
_headers: Headers
|
|
57
|
+
|
|
58
|
+
async def _request(
|
|
59
|
+
self,
|
|
60
|
+
method: RequestMethod,
|
|
61
|
+
path: list[str],
|
|
62
|
+
headers: dict[str, Any] | None = None,
|
|
63
|
+
json: dict[Any, Any] | None = None,
|
|
64
|
+
files: Any | None = None,
|
|
65
|
+
query_params: dict[str, str] | None = None,
|
|
66
|
+
**kwargs: Any,
|
|
67
|
+
) -> Response:
|
|
68
|
+
try:
|
|
69
|
+
url_path = self._base_url.joinpath(*path).with_query(query_params)
|
|
70
|
+
request_headers = Headers(self._headers)
|
|
71
|
+
for name, value in (headers or {}).items():
|
|
72
|
+
request_headers[name] = value
|
|
73
|
+
response = await self._client.request(
|
|
74
|
+
method,
|
|
75
|
+
str(url_path),
|
|
76
|
+
headers=request_headers,
|
|
77
|
+
json=json,
|
|
78
|
+
files=files,
|
|
79
|
+
**kwargs,
|
|
80
|
+
)
|
|
81
|
+
response.raise_for_status()
|
|
82
|
+
except HTTPStatusError as exc:
|
|
83
|
+
try:
|
|
84
|
+
resp = exc.response.json()
|
|
85
|
+
raise StorageApiError(
|
|
86
|
+
resp["message"], resp["error"], resp["statusCode"]
|
|
87
|
+
) from exc
|
|
88
|
+
except (KeyError, TypeError, ValueError) as err:
|
|
89
|
+
message = f"Unable to parse error message: {exc.response.text}"
|
|
90
|
+
raise StorageApiError(
|
|
91
|
+
message, "InternalError", exc.response.status_code
|
|
92
|
+
) from err
|
|
93
|
+
|
|
94
|
+
return response
|
|
95
|
+
|
|
96
|
+
async def create_signed_upload_url(
|
|
97
|
+
self,
|
|
98
|
+
path: str,
|
|
99
|
+
options: CreateSignedUploadUrlOptions | None = None,
|
|
100
|
+
) -> SignedUploadURL:
|
|
101
|
+
"""
|
|
102
|
+
Creates a signed upload URL.
|
|
103
|
+
|
|
104
|
+
Parameters
|
|
105
|
+
----------
|
|
106
|
+
path
|
|
107
|
+
The file path, including the file name. For example `folder/image.png`.
|
|
108
|
+
options
|
|
109
|
+
Additional options for the upload url creation.
|
|
110
|
+
"""
|
|
111
|
+
headers: dict[str, str] = dict()
|
|
112
|
+
if options is not None and options.upsert:
|
|
113
|
+
headers.update({"x-upsert": options.upsert})
|
|
114
|
+
|
|
115
|
+
path_parts = relative_path_to_parts(path)
|
|
116
|
+
response = await self._request(
|
|
117
|
+
"POST", ["object", "upload", "sign", self.id, *path_parts], headers=headers
|
|
118
|
+
)
|
|
119
|
+
data = response.json()
|
|
120
|
+
full_url: urllib.parse.ParseResult = urllib.parse.urlparse(
|
|
121
|
+
str(self._base_url) + cast(str, data["url"]).lstrip("/")
|
|
122
|
+
)
|
|
123
|
+
query_params = urllib.parse.parse_qs(full_url.query)
|
|
124
|
+
if not query_params.get("token"):
|
|
125
|
+
raise StorageException("No token sent by the API")
|
|
126
|
+
return {
|
|
127
|
+
"signed_url": full_url.geturl(),
|
|
128
|
+
"signedUrl": full_url.geturl(),
|
|
129
|
+
"token": query_params["token"][0],
|
|
130
|
+
"path": path,
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async def upload_to_signed_url(
|
|
134
|
+
self,
|
|
135
|
+
path: str,
|
|
136
|
+
token: str,
|
|
137
|
+
file: BufferedReader | bytes | FileIO | str | Path,
|
|
138
|
+
file_options: UploadSignedUrlFileOptions | None = None,
|
|
139
|
+
) -> UploadResponse:
|
|
140
|
+
"""
|
|
141
|
+
Upload a file with a token generated from :meth:`.create_signed_url`
|
|
142
|
+
|
|
143
|
+
Parameters
|
|
144
|
+
----------
|
|
145
|
+
path
|
|
146
|
+
The file path, including the file name
|
|
147
|
+
token
|
|
148
|
+
The token generated from :meth:`.create_signed_url`
|
|
149
|
+
file
|
|
150
|
+
The file contents or a file-like object to upload
|
|
151
|
+
file_options
|
|
152
|
+
Additional options for the uploaded file
|
|
153
|
+
"""
|
|
154
|
+
path_parts = relative_path_to_parts(path)
|
|
155
|
+
query_params = {"token": token}
|
|
156
|
+
|
|
157
|
+
final_url = ["object", "upload", "sign", self.id, *path_parts]
|
|
158
|
+
|
|
159
|
+
options: dict[str, Any] = {
|
|
160
|
+
**DEFAULT_FILE_OPTIONS,
|
|
161
|
+
**(file_options or {}),
|
|
162
|
+
}
|
|
163
|
+
cache_control = options.pop("cache-control")
|
|
164
|
+
content_type = options.pop("content-type")
|
|
165
|
+
metadata = options.pop("metadata", None)
|
|
166
|
+
file_opts_headers = options.pop("headers", None)
|
|
167
|
+
|
|
168
|
+
_data = {"cacheControl": cache_control}
|
|
169
|
+
if metadata is not None:
|
|
170
|
+
_data["metadata"] = json.dumps(metadata)
|
|
171
|
+
|
|
172
|
+
headers = dict(options)
|
|
173
|
+
if file_opts_headers:
|
|
174
|
+
headers.update(file_opts_headers)
|
|
175
|
+
|
|
176
|
+
filename = path_parts[-1]
|
|
177
|
+
|
|
178
|
+
if (
|
|
179
|
+
isinstance(file, BufferedReader)
|
|
180
|
+
or isinstance(file, bytes)
|
|
181
|
+
or isinstance(file, FileIO)
|
|
182
|
+
):
|
|
183
|
+
# bytes or byte-stream-like object received -- the caller owns it
|
|
184
|
+
opened = None
|
|
185
|
+
_file = {"file": (filename, file, content_type)}
|
|
186
|
+
else:
|
|
187
|
+
# str or pathlib.path received -- we own the handle, so we close it
|
|
188
|
+
opened = open(file, "rb")
|
|
189
|
+
_file = {"file": (filename, opened, content_type)}
|
|
190
|
+
|
|
191
|
+
try:
|
|
192
|
+
response = await self._request(
|
|
193
|
+
"PUT",
|
|
194
|
+
final_url,
|
|
195
|
+
files=_file,
|
|
196
|
+
headers=headers,
|
|
197
|
+
data=_data,
|
|
198
|
+
query_params=query_params,
|
|
199
|
+
)
|
|
200
|
+
finally:
|
|
201
|
+
if opened is not None:
|
|
202
|
+
opened.close()
|
|
203
|
+
|
|
204
|
+
data: UploadData = response.json()
|
|
205
|
+
|
|
206
|
+
return UploadResponse(path=path, Key=data["Key"])
|
|
207
|
+
|
|
208
|
+
def _make_signed_url(
|
|
209
|
+
self, signed_url: str | None, download_query: dict[str, str]
|
|
210
|
+
) -> SignedUrlResponse:
|
|
211
|
+
if signed_url is None:
|
|
212
|
+
return {"signedURL": None, "signedUrl": None}
|
|
213
|
+
url = URL(signed_url[1:]) # ignore starting slash
|
|
214
|
+
signedURL = self._base_url.join(url).extend_query(download_query)
|
|
215
|
+
return {"signedURL": str(signedURL), "signedUrl": str(signedURL)}
|
|
216
|
+
|
|
217
|
+
async def create_signed_url(
|
|
218
|
+
self, path: str, expires_in: int, options: URLOptions | None = None
|
|
219
|
+
) -> SignedUrlResponse:
|
|
220
|
+
"""
|
|
221
|
+
Parameters
|
|
222
|
+
----------
|
|
223
|
+
path
|
|
224
|
+
file path to be downloaded, including the current file name.
|
|
225
|
+
expires_in
|
|
226
|
+
number of seconds until the signed URL expires.
|
|
227
|
+
options
|
|
228
|
+
options to be passed for downloading or transforming the file.
|
|
229
|
+
"""
|
|
230
|
+
json: dict[str, str | bool | TransformOptions] = {"expiresIn": str(expires_in)}
|
|
231
|
+
download_query = {}
|
|
232
|
+
url_options = options or {}
|
|
233
|
+
if download := url_options.get("download"):
|
|
234
|
+
json.update({"download": download})
|
|
235
|
+
download_query = {"download": "" if download is True else download}
|
|
236
|
+
if transform := url_options.get("transform"):
|
|
237
|
+
json.update({"transform": transform})
|
|
238
|
+
|
|
239
|
+
path_parts = relative_path_to_parts(path)
|
|
240
|
+
response = await self._request(
|
|
241
|
+
"POST",
|
|
242
|
+
["object", "sign", self.id, *path_parts],
|
|
243
|
+
json=json,
|
|
244
|
+
)
|
|
245
|
+
|
|
246
|
+
data = SignedUrlJsonResponse.model_validate_json(response.content)
|
|
247
|
+
return self._make_signed_url(data.signedURL, download_query)
|
|
248
|
+
|
|
249
|
+
async def create_signed_urls(
|
|
250
|
+
self,
|
|
251
|
+
paths: builtins.list[str],
|
|
252
|
+
expires_in: int,
|
|
253
|
+
options: CreateSignedURLsOptions | None = None,
|
|
254
|
+
) -> builtins.list[CreateSignedUrlResponse]:
|
|
255
|
+
"""
|
|
256
|
+
Parameters
|
|
257
|
+
----------
|
|
258
|
+
path
|
|
259
|
+
file path to be downloaded, including the current file name.
|
|
260
|
+
expires_in
|
|
261
|
+
number of seconds until the signed URL expires.
|
|
262
|
+
options
|
|
263
|
+
options to be passed for downloading the file.
|
|
264
|
+
"""
|
|
265
|
+
json: dict[str, str | bool | None | list[str]] = {
|
|
266
|
+
"paths": paths,
|
|
267
|
+
"expiresIn": str(expires_in),
|
|
268
|
+
}
|
|
269
|
+
download_query = {}
|
|
270
|
+
url_options = options or {}
|
|
271
|
+
if download := url_options.get("download"):
|
|
272
|
+
json.update({"download": download})
|
|
273
|
+
download_query = {"download": "" if download is True else download}
|
|
274
|
+
|
|
275
|
+
response = await self._request(
|
|
276
|
+
"POST",
|
|
277
|
+
["object", "sign", self.id],
|
|
278
|
+
json=json,
|
|
279
|
+
)
|
|
280
|
+
data = SignedUrlsJsonResponse.validate_json(response.content)
|
|
281
|
+
signed_urls = []
|
|
282
|
+
for item in data:
|
|
283
|
+
# Prepare URL
|
|
284
|
+
url = self._make_signed_url(item.signedURL, download_query)
|
|
285
|
+
signed_item: CreateSignedUrlResponse = {
|
|
286
|
+
"error": item.error,
|
|
287
|
+
"path": item.path,
|
|
288
|
+
"signedURL": url["signedURL"],
|
|
289
|
+
"signedUrl": url["signedURL"],
|
|
290
|
+
}
|
|
291
|
+
signed_urls.append(signed_item)
|
|
292
|
+
return signed_urls
|
|
293
|
+
|
|
294
|
+
async def get_public_url(self, path: str, options: URLOptions | None = None) -> str:
|
|
295
|
+
"""
|
|
296
|
+
Parameters
|
|
297
|
+
----------
|
|
298
|
+
path
|
|
299
|
+
file path, including the path and file name. For example `folder/image.png`.
|
|
300
|
+
"""
|
|
301
|
+
download_query = {}
|
|
302
|
+
url_options = options or {}
|
|
303
|
+
if download := url_options.get("download"):
|
|
304
|
+
download_query = {"download": "" if download is True else download}
|
|
305
|
+
|
|
306
|
+
render_path = (
|
|
307
|
+
["render", "image"] if url_options.get("transform") else ["object"]
|
|
308
|
+
)
|
|
309
|
+
transformation = (
|
|
310
|
+
transform_to_dict(t) if (t := url_options.get("transform")) else dict()
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
path_parts = relative_path_to_parts(path)
|
|
314
|
+
url = (
|
|
315
|
+
self._base_url.joinpath(*render_path, "public", self.id, *path_parts)
|
|
316
|
+
.with_query(download_query)
|
|
317
|
+
.extend_query(transformation)
|
|
318
|
+
)
|
|
319
|
+
return str(url)
|
|
320
|
+
|
|
321
|
+
async def move(self, from_path: str, to_path: str) -> dict[str, str]:
|
|
322
|
+
"""
|
|
323
|
+
Moves an existing file, optionally renaming it at the same time.
|
|
324
|
+
|
|
325
|
+
Parameters
|
|
326
|
+
----------
|
|
327
|
+
from_path
|
|
328
|
+
The original file path, including the current file name. For example `folder/image.png`.
|
|
329
|
+
to_path
|
|
330
|
+
The new file path, including the new file name. For example `folder/image-copy.png`.
|
|
331
|
+
"""
|
|
332
|
+
res = await self._request(
|
|
333
|
+
"POST",
|
|
334
|
+
["object", "move"],
|
|
335
|
+
json={
|
|
336
|
+
"bucketId": self.id,
|
|
337
|
+
"sourceKey": from_path,
|
|
338
|
+
"destinationKey": to_path,
|
|
339
|
+
},
|
|
340
|
+
)
|
|
341
|
+
return res.json()
|
|
342
|
+
|
|
343
|
+
async def copy(self, from_path: str, to_path: str) -> dict[str, str]:
|
|
344
|
+
"""
|
|
345
|
+
Copies an existing file to a new path in the same bucket.
|
|
346
|
+
|
|
347
|
+
Parameters
|
|
348
|
+
----------
|
|
349
|
+
from_path
|
|
350
|
+
The original file path, including the current file name. For example `folder/image.png`.
|
|
351
|
+
to_path
|
|
352
|
+
The new file path, including the new file name. For example `folder/image-copy.png`.
|
|
353
|
+
"""
|
|
354
|
+
res = await self._request(
|
|
355
|
+
"POST",
|
|
356
|
+
["object", "copy"],
|
|
357
|
+
json={
|
|
358
|
+
"bucketId": self.id,
|
|
359
|
+
"sourceKey": from_path,
|
|
360
|
+
"destinationKey": to_path,
|
|
361
|
+
},
|
|
362
|
+
)
|
|
363
|
+
return res.json()
|
|
364
|
+
|
|
365
|
+
async def remove(self, paths: list[str]) -> list[dict[str, Any]]:
|
|
366
|
+
"""
|
|
367
|
+
Deletes files within the same bucket
|
|
368
|
+
|
|
369
|
+
Parameters
|
|
370
|
+
----------
|
|
371
|
+
paths
|
|
372
|
+
An array or list of files to be deletes, including the path and file name. For example [`folder/image.png`].
|
|
373
|
+
"""
|
|
374
|
+
response = await self._request(
|
|
375
|
+
"DELETE",
|
|
376
|
+
["object", self.id],
|
|
377
|
+
json={"prefixes": paths},
|
|
378
|
+
)
|
|
379
|
+
return response.json()
|
|
380
|
+
|
|
381
|
+
async def info(
|
|
382
|
+
self,
|
|
383
|
+
path: str,
|
|
384
|
+
) -> dict[str, Any]:
|
|
385
|
+
"""
|
|
386
|
+
Lists info for a particular file.
|
|
387
|
+
|
|
388
|
+
Parameters
|
|
389
|
+
----------
|
|
390
|
+
path
|
|
391
|
+
The path to the file.
|
|
392
|
+
"""
|
|
393
|
+
path_parts = relative_path_to_parts(path) # split paths by /
|
|
394
|
+
response = await self._request(
|
|
395
|
+
"GET",
|
|
396
|
+
["object", "info", self.id, *path_parts],
|
|
397
|
+
)
|
|
398
|
+
return response.json()
|
|
399
|
+
|
|
400
|
+
async def exists(
|
|
401
|
+
self,
|
|
402
|
+
path: str,
|
|
403
|
+
) -> bool:
|
|
404
|
+
"""
|
|
405
|
+
Returns True if the file exists, False otherwise.
|
|
406
|
+
|
|
407
|
+
This reads the object's info, so the result is False only when Storage
|
|
408
|
+
reports that the object does not exist. Any other failure, such as an
|
|
409
|
+
invalid JWT or a missing bucket, raises.
|
|
410
|
+
|
|
411
|
+
Parameters
|
|
412
|
+
----------
|
|
413
|
+
path
|
|
414
|
+
The path to the file.
|
|
415
|
+
"""
|
|
416
|
+
try:
|
|
417
|
+
await self.info(path)
|
|
418
|
+
return True
|
|
419
|
+
except StorageApiError as exc:
|
|
420
|
+
# A HEAD response has no body, so it can't tell an invalid JWT or a
|
|
421
|
+
# missing bucket apart from a missing object. The info response
|
|
422
|
+
# can: a missing object is a 404 "not_found", or a 404 without a
|
|
423
|
+
# parsable body.
|
|
424
|
+
if str(exc.status) == "404" and exc.code in ("not_found", "InternalError"):
|
|
425
|
+
return False
|
|
426
|
+
raise
|
|
427
|
+
|
|
428
|
+
async def list(
|
|
429
|
+
self,
|
|
430
|
+
path: str | None = None,
|
|
431
|
+
options: ListBucketFilesOptions | None = None,
|
|
432
|
+
) -> list[dict[str, Any]]:
|
|
433
|
+
"""
|
|
434
|
+
Lists all the files within a bucket.
|
|
435
|
+
|
|
436
|
+
Parameters
|
|
437
|
+
----------
|
|
438
|
+
path
|
|
439
|
+
The folder path.
|
|
440
|
+
options
|
|
441
|
+
Search options, including `limit`, `offset`, `sortBy` and `search`.
|
|
442
|
+
"""
|
|
443
|
+
extra_options = options or {}
|
|
444
|
+
extra_headers = {"Content-Type": "application/json"}
|
|
445
|
+
body = {
|
|
446
|
+
**DEFAULT_SEARCH_OPTIONS,
|
|
447
|
+
**extra_options,
|
|
448
|
+
"sortBy": {
|
|
449
|
+
**DEFAULT_SORT_BY,
|
|
450
|
+
**extra_options.get("sortBy", {}),
|
|
451
|
+
},
|
|
452
|
+
"prefix": path or "",
|
|
453
|
+
}
|
|
454
|
+
response = await self._request(
|
|
455
|
+
"POST",
|
|
456
|
+
["object", "list", self.id],
|
|
457
|
+
json=body,
|
|
458
|
+
headers=extra_headers,
|
|
459
|
+
)
|
|
460
|
+
return response.json()
|
|
461
|
+
|
|
462
|
+
async def list_v2(
|
|
463
|
+
self,
|
|
464
|
+
options: SearchV2Options | None = None,
|
|
465
|
+
) -> SearchV2Result:
|
|
466
|
+
body = {**options} if options else {}
|
|
467
|
+
response = await self._request(
|
|
468
|
+
"POST",
|
|
469
|
+
["object", "list-v2", self.id],
|
|
470
|
+
json=body,
|
|
471
|
+
)
|
|
472
|
+
return SearchV2Result.model_validate_json(response.content)
|
|
473
|
+
|
|
474
|
+
async def download(
|
|
475
|
+
self,
|
|
476
|
+
path: str,
|
|
477
|
+
options: DownloadOptions | None = None,
|
|
478
|
+
query_params: dict[str, str] | None = None,
|
|
479
|
+
) -> bytes:
|
|
480
|
+
"""
|
|
481
|
+
Downloads a file.
|
|
482
|
+
|
|
483
|
+
Parameters
|
|
484
|
+
----------
|
|
485
|
+
path
|
|
486
|
+
The file path to be downloaded, including the path and file name. For example `folder/image.png`.
|
|
487
|
+
"""
|
|
488
|
+
url_options = options or DownloadOptions()
|
|
489
|
+
render_path = (
|
|
490
|
+
["render", "image", "authenticated"]
|
|
491
|
+
if url_options.get("transform")
|
|
492
|
+
else ["object"]
|
|
493
|
+
)
|
|
494
|
+
|
|
495
|
+
transform_options = url_options.get("transform") or TransformOptions()
|
|
496
|
+
|
|
497
|
+
path_parts = relative_path_to_parts(path)
|
|
498
|
+
response = await self._request(
|
|
499
|
+
"GET",
|
|
500
|
+
[*render_path, self.id, *path_parts],
|
|
501
|
+
query_params={
|
|
502
|
+
**transform_to_dict(transform_options),
|
|
503
|
+
**(query_params or {}),
|
|
504
|
+
},
|
|
505
|
+
)
|
|
506
|
+
return response.content
|
|
507
|
+
|
|
508
|
+
async def _upload_or_update(
|
|
509
|
+
self,
|
|
510
|
+
method: Literal["POST", "PUT"],
|
|
511
|
+
path: tuple[str, ...],
|
|
512
|
+
file: BufferedReader | bytes | FileIO | str | Path,
|
|
513
|
+
file_options: FileOptions | None = None,
|
|
514
|
+
) -> UploadResponse:
|
|
515
|
+
"""
|
|
516
|
+
Uploads a file to an existing bucket.
|
|
517
|
+
|
|
518
|
+
Parameters
|
|
519
|
+
----------
|
|
520
|
+
path
|
|
521
|
+
The relative file path including the bucket ID. Should be of the format `bucket/folder/subfolder/filename.png`.
|
|
522
|
+
The bucket must already exist before attempting to upload.
|
|
523
|
+
file
|
|
524
|
+
The File object to be stored in the bucket. or a async generator of chunks
|
|
525
|
+
file_options
|
|
526
|
+
HTTP headers.
|
|
527
|
+
"""
|
|
528
|
+
options: dict[str, Any] = {
|
|
529
|
+
**DEFAULT_FILE_OPTIONS,
|
|
530
|
+
**(file_options or {}),
|
|
531
|
+
}
|
|
532
|
+
cache_control = options.pop("cache-control")
|
|
533
|
+
content_type = options.pop("content-type")
|
|
534
|
+
_data = {"cacheControl": cache_control}
|
|
535
|
+
|
|
536
|
+
upsert = options.pop("upsert", None)
|
|
537
|
+
if upsert:
|
|
538
|
+
options["x-upsert"] = upsert
|
|
539
|
+
|
|
540
|
+
metadata = options.pop("metadata", None)
|
|
541
|
+
file_opts_headers = options.pop("headers", None)
|
|
542
|
+
|
|
543
|
+
headers = dict(options)
|
|
544
|
+
|
|
545
|
+
if metadata is not None:
|
|
546
|
+
metadata_str = json.dumps(metadata)
|
|
547
|
+
_data["metadata"] = metadata_str
|
|
548
|
+
|
|
549
|
+
# Only include x-upsert on a POST method
|
|
550
|
+
if method != "POST":
|
|
551
|
+
headers.pop("x-upsert", None)
|
|
552
|
+
|
|
553
|
+
if file_opts_headers:
|
|
554
|
+
headers.update(file_opts_headers)
|
|
555
|
+
|
|
556
|
+
filename = path[-1]
|
|
557
|
+
|
|
558
|
+
if (
|
|
559
|
+
isinstance(file, BufferedReader)
|
|
560
|
+
or isinstance(file, bytes)
|
|
561
|
+
or isinstance(file, FileIO)
|
|
562
|
+
):
|
|
563
|
+
# bytes or byte-stream-like object received -- the caller owns it
|
|
564
|
+
opened = None
|
|
565
|
+
files = {"file": (filename, file, content_type)}
|
|
566
|
+
else:
|
|
567
|
+
# str or pathlib.path received -- we own the handle, so we close it
|
|
568
|
+
opened = open(file, "rb")
|
|
569
|
+
files = {"file": (filename, opened, content_type)}
|
|
570
|
+
|
|
571
|
+
try:
|
|
572
|
+
response = await self._request(
|
|
573
|
+
method,
|
|
574
|
+
["object", self.id, *path],
|
|
575
|
+
files=files,
|
|
576
|
+
headers=headers,
|
|
577
|
+
data=_data,
|
|
578
|
+
)
|
|
579
|
+
finally:
|
|
580
|
+
if opened is not None:
|
|
581
|
+
opened.close()
|
|
582
|
+
|
|
583
|
+
data: UploadData = response.json()
|
|
584
|
+
|
|
585
|
+
return UploadResponse(path="/".join(path), Key=data["Key"])
|
|
586
|
+
|
|
587
|
+
async def upload(
|
|
588
|
+
self,
|
|
589
|
+
path: str,
|
|
590
|
+
file: BufferedReader | bytes | FileIO | str | Path,
|
|
591
|
+
file_options: FileOptions | None = None,
|
|
592
|
+
) -> UploadResponse:
|
|
593
|
+
"""
|
|
594
|
+
Uploads a file to an existing bucket.
|
|
595
|
+
|
|
596
|
+
Parameters
|
|
597
|
+
----------
|
|
598
|
+
path
|
|
599
|
+
The relative file path including the bucket ID. Should be of the format `bucket/folder/subfolder/filename.png`.
|
|
600
|
+
The bucket must already exist before attempting to upload.
|
|
601
|
+
file
|
|
602
|
+
The File object to be stored in the bucket. or a async generator of chunks
|
|
603
|
+
file_options
|
|
604
|
+
HTTP headers.
|
|
605
|
+
"""
|
|
606
|
+
path_parts = relative_path_to_parts(path)
|
|
607
|
+
return await self._upload_or_update("POST", path_parts, file, file_options)
|
|
608
|
+
|
|
609
|
+
async def update(
|
|
610
|
+
self,
|
|
611
|
+
path: str,
|
|
612
|
+
file: BufferedReader | bytes | FileIO | str | Path,
|
|
613
|
+
file_options: FileOptions | None = None,
|
|
614
|
+
) -> UploadResponse:
|
|
615
|
+
path_parts = relative_path_to_parts(path)
|
|
616
|
+
return await self._upload_or_update("PUT", path_parts, file, file_options)
|
|
617
|
+
|
|
618
|
+
|
|
619
|
+
class AsyncBucket(BaseBucket):
|
|
620
|
+
"""Represents a storage bucket."""
|
|
621
|
+
|
|
622
|
+
|
|
623
|
+
@dataclass
|
|
624
|
+
class AsyncBucketProxy(AsyncBucketActionsMixin):
|
|
625
|
+
"""A bucket proxy, this contains the minimum required fields to query the File API."""
|
|
626
|
+
|
|
627
|
+
id: str
|
|
628
|
+
_base_url: URL
|
|
629
|
+
_headers: Headers
|
|
630
|
+
_client: AsyncClient = field(repr=False)
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
from httpx import AsyncClient, Headers, HTTPStatusError, QueryParams, Response
|
|
2
|
+
from yarl import URL
|
|
3
|
+
|
|
4
|
+
from ..exceptions import _parse_storage_api_error
|
|
5
|
+
from ..types import JSON, RequestMethod
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class AsyncRequestBuilder:
|
|
9
|
+
def __init__(self, session: AsyncClient, base_url: URL, headers: Headers) -> None:
|
|
10
|
+
self._session = session
|
|
11
|
+
self._base_url = base_url
|
|
12
|
+
self.headers = headers
|
|
13
|
+
|
|
14
|
+
async def send(
|
|
15
|
+
self,
|
|
16
|
+
http_method: RequestMethod,
|
|
17
|
+
path: list[str],
|
|
18
|
+
body: JSON = None,
|
|
19
|
+
query_params: QueryParams | None = None,
|
|
20
|
+
) -> Response:
|
|
21
|
+
response = await self._session.request(
|
|
22
|
+
method=http_method,
|
|
23
|
+
json=body,
|
|
24
|
+
url=str(self._base_url.joinpath(*path)),
|
|
25
|
+
headers=self.headers,
|
|
26
|
+
params=query_params or QueryParams(),
|
|
27
|
+
)
|
|
28
|
+
try:
|
|
29
|
+
response.raise_for_status()
|
|
30
|
+
return response
|
|
31
|
+
except HTTPStatusError as exc:
|
|
32
|
+
raise _parse_storage_api_error(response) from exc
|