bigbucket-sdk 0.1.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.
- bigbucket/__init__.py +77 -0
- bigbucket/_normalize.py +328 -0
- bigbucket/client.py +273 -0
- bigbucket/errors.py +157 -0
- bigbucket/py.typed +0 -0
- bigbucket/resources/__init__.py +14 -0
- bigbucket/resources/images.py +103 -0
- bigbucket/resources/uploads.py +233 -0
- bigbucket/resources/usage.py +34 -0
- bigbucket/transform.py +79 -0
- bigbucket/transport.py +253 -0
- bigbucket/types.py +103 -0
- bigbucket_sdk-0.1.0.dist-info/METADATA +179 -0
- bigbucket_sdk-0.1.0.dist-info/RECORD +16 -0
- bigbucket_sdk-0.1.0.dist-info/WHEEL +5 -0
- bigbucket_sdk-0.1.0.dist-info/top_level.txt +1 -0
bigbucket/__init__.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"""Official BigBucket Python SDK for Flask, FastAPI, and Django."""
|
|
2
|
+
|
|
3
|
+
from .client import AsyncBigBucket, BigBucket
|
|
4
|
+
from .errors import (
|
|
5
|
+
AuthenticationError,
|
|
6
|
+
BigBucketError,
|
|
7
|
+
NotFoundError,
|
|
8
|
+
PayloadTooLargeError,
|
|
9
|
+
RateLimitError,
|
|
10
|
+
StorageUploadError,
|
|
11
|
+
TimeoutError,
|
|
12
|
+
UnsupportedFormatError,
|
|
13
|
+
)
|
|
14
|
+
from .resources import (
|
|
15
|
+
AsyncImagesResource,
|
|
16
|
+
AsyncUploadsResource,
|
|
17
|
+
AsyncUsageResource,
|
|
18
|
+
ImagesResource,
|
|
19
|
+
UploadsResource,
|
|
20
|
+
UsageResource,
|
|
21
|
+
)
|
|
22
|
+
from .transform import build_transform_url
|
|
23
|
+
from .types import (
|
|
24
|
+
DeleteResult,
|
|
25
|
+
FileInput,
|
|
26
|
+
ImageAsset,
|
|
27
|
+
ImageFormat,
|
|
28
|
+
ImageStatus,
|
|
29
|
+
ImageVariant,
|
|
30
|
+
PaginatedImages,
|
|
31
|
+
Pagination,
|
|
32
|
+
PresignedDetails,
|
|
33
|
+
TransformFit,
|
|
34
|
+
TransformFormat,
|
|
35
|
+
UploadMode,
|
|
36
|
+
UploadSession,
|
|
37
|
+
UploadStatus,
|
|
38
|
+
UsageSummary,
|
|
39
|
+
)
|
|
40
|
+
|
|
41
|
+
__version__ = "0.1.0"
|
|
42
|
+
|
|
43
|
+
__all__ = [
|
|
44
|
+
"BigBucket",
|
|
45
|
+
"AsyncBigBucket",
|
|
46
|
+
"build_transform_url",
|
|
47
|
+
"ImagesResource",
|
|
48
|
+
"AsyncImagesResource",
|
|
49
|
+
"UploadsResource",
|
|
50
|
+
"AsyncUploadsResource",
|
|
51
|
+
"UsageResource",
|
|
52
|
+
"AsyncUsageResource",
|
|
53
|
+
"BigBucketError",
|
|
54
|
+
"AuthenticationError",
|
|
55
|
+
"NotFoundError",
|
|
56
|
+
"PayloadTooLargeError",
|
|
57
|
+
"UnsupportedFormatError",
|
|
58
|
+
"RateLimitError",
|
|
59
|
+
"StorageUploadError",
|
|
60
|
+
"TimeoutError",
|
|
61
|
+
"DeleteResult",
|
|
62
|
+
"FileInput",
|
|
63
|
+
"ImageAsset",
|
|
64
|
+
"ImageFormat",
|
|
65
|
+
"ImageStatus",
|
|
66
|
+
"ImageVariant",
|
|
67
|
+
"PaginatedImages",
|
|
68
|
+
"Pagination",
|
|
69
|
+
"PresignedDetails",
|
|
70
|
+
"TransformFit",
|
|
71
|
+
"TransformFormat",
|
|
72
|
+
"UploadMode",
|
|
73
|
+
"UploadSession",
|
|
74
|
+
"UploadStatus",
|
|
75
|
+
"UsageSummary",
|
|
76
|
+
"__version__",
|
|
77
|
+
]
|
bigbucket/_normalize.py
ADDED
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
"""Internal request builders, file resolvers, and response mappers."""
|
|
2
|
+
|
|
3
|
+
import mimetypes
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
from typing import Any, Dict, List, Optional, Tuple
|
|
6
|
+
from urllib.parse import quote, urlencode
|
|
7
|
+
|
|
8
|
+
from .errors import (
|
|
9
|
+
AuthenticationError,
|
|
10
|
+
BigBucketError,
|
|
11
|
+
NotFoundError,
|
|
12
|
+
PayloadTooLargeError,
|
|
13
|
+
RateLimitError,
|
|
14
|
+
UnsupportedFormatError,
|
|
15
|
+
)
|
|
16
|
+
from .types import (
|
|
17
|
+
DeleteResult,
|
|
18
|
+
FileInput,
|
|
19
|
+
ImageAsset,
|
|
20
|
+
PaginatedImages,
|
|
21
|
+
UploadSession,
|
|
22
|
+
UploadStatus,
|
|
23
|
+
UsageSummary,
|
|
24
|
+
)
|
|
25
|
+
|
|
26
|
+
_EXT_MIME_FALLBACKS: Dict[str, str] = {
|
|
27
|
+
".jpg": "image/jpeg",
|
|
28
|
+
".jpeg": "image/jpeg",
|
|
29
|
+
".png": "image/png",
|
|
30
|
+
".webp": "image/webp",
|
|
31
|
+
".avif": "image/avif",
|
|
32
|
+
".gif": "image/gif",
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def guess_content_type(filename: Optional[str]) -> str:
|
|
37
|
+
"""Infer MIME type from filename, defaulting to image/jpeg when unknown."""
|
|
38
|
+
if filename:
|
|
39
|
+
ext = Path(filename).suffix.lower()
|
|
40
|
+
if ext in _EXT_MIME_FALLBACKS:
|
|
41
|
+
return _EXT_MIME_FALLBACKS[ext]
|
|
42
|
+
guessed, _ = mimetypes.guess_type(filename)
|
|
43
|
+
if guessed:
|
|
44
|
+
return guessed
|
|
45
|
+
return "application/octet-stream"
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def resolve_file_data(
|
|
49
|
+
file: FileInput,
|
|
50
|
+
*,
|
|
51
|
+
filename: Optional[str] = None,
|
|
52
|
+
content_type: Optional[str] = None,
|
|
53
|
+
file_size: Optional[int] = None,
|
|
54
|
+
) -> Tuple[bytes, str, str, int]:
|
|
55
|
+
"""Normalize bytes, Paths, strings, or file-like objects into raw bytes & metadata."""
|
|
56
|
+
inferred_name = filename
|
|
57
|
+
|
|
58
|
+
if isinstance(file, (bytes, bytearray)):
|
|
59
|
+
raw_bytes = bytes(file)
|
|
60
|
+
elif isinstance(file, memoryview):
|
|
61
|
+
raw_bytes = file.tobytes()
|
|
62
|
+
elif isinstance(file, Path):
|
|
63
|
+
inferred_name = inferred_name or file.name
|
|
64
|
+
raw_bytes = file.read_bytes()
|
|
65
|
+
elif isinstance(file, str):
|
|
66
|
+
path = Path(file)
|
|
67
|
+
if path.exists() and path.is_file():
|
|
68
|
+
inferred_name = inferred_name or path.name
|
|
69
|
+
raw_bytes = path.read_bytes()
|
|
70
|
+
else:
|
|
71
|
+
raw_bytes = file.encode("utf-8")
|
|
72
|
+
elif hasattr(file, "read") and callable(file.read):
|
|
73
|
+
stream_name = getattr(file, "name", None)
|
|
74
|
+
if not inferred_name and isinstance(stream_name, (str, Path)):
|
|
75
|
+
inferred_name = Path(stream_name).name
|
|
76
|
+
content = file.read()
|
|
77
|
+
raw_bytes = content.encode("utf-8") if isinstance(content, str) else bytes(content)
|
|
78
|
+
else:
|
|
79
|
+
raise TypeError(
|
|
80
|
+
"Unsupported file input. Pass bytes, bytearray, pathlib.Path, file path string, or a readable binary stream."
|
|
81
|
+
)
|
|
82
|
+
|
|
83
|
+
final_filename = inferred_name or "upload.bin"
|
|
84
|
+
final_mime = content_type or guess_content_type(final_filename)
|
|
85
|
+
final_size = file_size if file_size is not None else len(raw_bytes)
|
|
86
|
+
return raw_bytes, final_filename, final_mime, int(final_size)
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
def raise_for_api_error(
|
|
90
|
+
status_code: int,
|
|
91
|
+
response_body: Any,
|
|
92
|
+
*,
|
|
93
|
+
request_id: Optional[str] = None,
|
|
94
|
+
) -> None:
|
|
95
|
+
"""Parse Express or legacy error payloads and raise the matching BigBucketError."""
|
|
96
|
+
body = response_body if isinstance(response_body, dict) else {}
|
|
97
|
+
nested_err = body.get("error") if isinstance(body.get("error"), dict) else None
|
|
98
|
+
err_payload = nested_err if nested_err is not None else body
|
|
99
|
+
|
|
100
|
+
errors_list = body.get("errors")
|
|
101
|
+
first_err = (
|
|
102
|
+
errors_list[0]
|
|
103
|
+
if isinstance(errors_list, list) and errors_list and isinstance(errors_list[0], dict)
|
|
104
|
+
else {}
|
|
105
|
+
)
|
|
106
|
+
|
|
107
|
+
message = (
|
|
108
|
+
err_payload.get("message")
|
|
109
|
+
or body.get("message")
|
|
110
|
+
or f"Request failed with status {status_code}"
|
|
111
|
+
)
|
|
112
|
+
code = err_payload.get("code") or first_err.get("code") or "REQUEST_FAILED"
|
|
113
|
+
details = err_payload.get("details")
|
|
114
|
+
if details is None and isinstance(errors_list, list) and errors_list:
|
|
115
|
+
details = {"errors": errors_list}
|
|
116
|
+
|
|
117
|
+
req_id = err_payload.get("request_id") or request_id
|
|
118
|
+
|
|
119
|
+
if status_code == 401:
|
|
120
|
+
raise AuthenticationError(str(message), code=str(code), request_id=req_id, details=details)
|
|
121
|
+
if status_code == 404:
|
|
122
|
+
raise NotFoundError(str(message), code=str(code), request_id=req_id, details=details)
|
|
123
|
+
if status_code == 413:
|
|
124
|
+
raise PayloadTooLargeError(str(message), code=str(code), request_id=req_id, details=details)
|
|
125
|
+
if status_code == 415:
|
|
126
|
+
raise UnsupportedFormatError(str(message), code=str(code), request_id=req_id, details=details)
|
|
127
|
+
if status_code == 429:
|
|
128
|
+
raise RateLimitError(str(message), code=str(code), request_id=req_id, details=details)
|
|
129
|
+
|
|
130
|
+
raise BigBucketError(
|
|
131
|
+
str(message),
|
|
132
|
+
status_code=status_code,
|
|
133
|
+
code=str(code),
|
|
134
|
+
request_id=req_id,
|
|
135
|
+
details=details,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def map_image_asset(d: Dict[str, Any]) -> ImageAsset:
|
|
140
|
+
"""Normalize Express MediaService asset payload into a clean ImageAsset dict."""
|
|
141
|
+
raw_status = d.get("status", "ready")
|
|
142
|
+
status_str = raw_status.lower() if isinstance(raw_status, str) else "ready"
|
|
143
|
+
|
|
144
|
+
raw_variants = d.get("variants") or []
|
|
145
|
+
variants = []
|
|
146
|
+
for v in raw_variants:
|
|
147
|
+
fmt = v.get("format") or ""
|
|
148
|
+
variants.append(
|
|
149
|
+
{
|
|
150
|
+
"variantName": v.get("variantName") or v.get("variant_name") or v.get("transformationKey") or "",
|
|
151
|
+
"url": v.get("url") or "",
|
|
152
|
+
"mimeType": v.get("mimeType") or v.get("mime_type") or (f"image/{fmt}" if fmt else ""),
|
|
153
|
+
"fileSize": int(v.get("fileSize") if v.get("fileSize") is not None else v.get("file_size", 0)),
|
|
154
|
+
"width": int(v.get("width") or 0),
|
|
155
|
+
"height": int(v.get("height") or 0),
|
|
156
|
+
"format": fmt,
|
|
157
|
+
}
|
|
158
|
+
)
|
|
159
|
+
|
|
160
|
+
return {
|
|
161
|
+
"id": d.get("id") or d.get("asset_uuid") or "",
|
|
162
|
+
"projectId": d.get("projectId") or d.get("project_id") or "",
|
|
163
|
+
"url": d.get("url") or d.get("cdnUrl") or d.get("delivery_url") or "",
|
|
164
|
+
"originalFilename": (
|
|
165
|
+
d.get("originalFilename")
|
|
166
|
+
or d.get("originalName")
|
|
167
|
+
or d.get("original_filename")
|
|
168
|
+
or d.get("filename")
|
|
169
|
+
or d.get("fileName")
|
|
170
|
+
or ""
|
|
171
|
+
),
|
|
172
|
+
"mimeType": d.get("mimeType") or d.get("mime_type") or d.get("content_type") or "",
|
|
173
|
+
"fileSize": int(
|
|
174
|
+
d.get("fileSize")
|
|
175
|
+
if d.get("fileSize") is not None
|
|
176
|
+
else d.get("file_size")
|
|
177
|
+
if d.get("file_size") is not None
|
|
178
|
+
else d.get("sizeBytes")
|
|
179
|
+
if d.get("sizeBytes") is not None
|
|
180
|
+
else d.get("size_bytes", 0)
|
|
181
|
+
),
|
|
182
|
+
"width": int(d.get("width") or 0),
|
|
183
|
+
"height": int(d.get("height") or 0),
|
|
184
|
+
"format": d.get("format") or "",
|
|
185
|
+
"status": status_str,
|
|
186
|
+
"createdAt": d.get("createdAt") or d.get("created_at") or "",
|
|
187
|
+
"updatedAt": d.get("updatedAt") or d.get("updated_at") or "",
|
|
188
|
+
"variants": variants,
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
|
|
192
|
+
def map_upload_session(d: Dict[str, Any]) -> UploadSession:
|
|
193
|
+
"""Normalize POST /uploads/intent response payload."""
|
|
194
|
+
session_id = d.get("uploadSessionId") or d.get("upload_id") or ""
|
|
195
|
+
mode = "GATEWAY" if d.get("mode") == "GATEWAY" else "DIRECT_R2"
|
|
196
|
+
presigned_raw = d.get("presigned") if isinstance(d.get("presigned"), dict) else {}
|
|
197
|
+
|
|
198
|
+
upload_url = d.get("uploadUrl") or d.get("gatewayUploadUrl") or presigned_raw.get("url") or ""
|
|
199
|
+
method = d.get("method") or presigned_raw.get("method") or ("POST" if mode == "GATEWAY" else "PUT")
|
|
200
|
+
headers = dict(d.get("headers") or presigned_raw.get("headers") or {})
|
|
201
|
+
file_key = d.get("fileKey") or d.get("object_key") or ""
|
|
202
|
+
|
|
203
|
+
return {
|
|
204
|
+
"uploadId": session_id,
|
|
205
|
+
"uploadSessionId": session_id,
|
|
206
|
+
"mode": mode,
|
|
207
|
+
"objectKey": file_key,
|
|
208
|
+
"fileKey": file_key,
|
|
209
|
+
"uploadUrl": upload_url,
|
|
210
|
+
"method": method,
|
|
211
|
+
"headers": headers,
|
|
212
|
+
"presigned": {
|
|
213
|
+
"url": upload_url,
|
|
214
|
+
"method": method,
|
|
215
|
+
"headers": headers,
|
|
216
|
+
},
|
|
217
|
+
"expiresAt": d.get("expiresAt") or d.get("expires_at") or "",
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def map_upload_status(d: Dict[str, Any]) -> UploadStatus:
|
|
222
|
+
"""Normalize GET /uploads/:sessionId response payload."""
|
|
223
|
+
session_id = d.get("uploadSessionId") or d.get("id") or ""
|
|
224
|
+
raw_asset = d.get("asset")
|
|
225
|
+
return {
|
|
226
|
+
"id": session_id,
|
|
227
|
+
"uploadSessionId": session_id,
|
|
228
|
+
"projectId": d.get("projectId") or d.get("project_id") or "",
|
|
229
|
+
"objectKey": d.get("objectKey") or d.get("fileKey") or d.get("object_key") or "",
|
|
230
|
+
"expectedFileSize": int(
|
|
231
|
+
d.get("expectedFileSize") if d.get("expectedFileSize") is not None else d.get("expected_file_size", 0)
|
|
232
|
+
),
|
|
233
|
+
"expectedMimeType": d.get("expectedMimeType") or d.get("expected_mime_type") or "",
|
|
234
|
+
"mode": d.get("mode"),
|
|
235
|
+
"status": str(d.get("status") or ""),
|
|
236
|
+
"expiresAt": d.get("expiresAt") or d.get("expires_at") or "",
|
|
237
|
+
"createdAt": d.get("createdAt") or d.get("created_at") or "",
|
|
238
|
+
"updatedAt": d.get("updatedAt") or d.get("updated_at"),
|
|
239
|
+
"completedAt": d.get("completedAt") or d.get("completed_at"),
|
|
240
|
+
"assetId": d.get("assetId") or d.get("asset_id"),
|
|
241
|
+
"asset": map_image_asset(raw_asset) if isinstance(raw_asset, dict) else None,
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def build_images_list_path(
|
|
246
|
+
*,
|
|
247
|
+
page: Optional[int] = None,
|
|
248
|
+
page_size: Optional[int] = None,
|
|
249
|
+
status: Optional[str] = None,
|
|
250
|
+
format: Optional[str] = None,
|
|
251
|
+
search: Optional[str] = None,
|
|
252
|
+
folder_id: Optional[str] = None,
|
|
253
|
+
project_id: Optional[str] = None,
|
|
254
|
+
) -> str:
|
|
255
|
+
params: List[Tuple[str, str]] = []
|
|
256
|
+
if page is not None:
|
|
257
|
+
params.append(("page", str(page)))
|
|
258
|
+
if page_size is not None:
|
|
259
|
+
params.append(("limit", str(page_size)))
|
|
260
|
+
if status is not None:
|
|
261
|
+
params.append(("status", status.upper()))
|
|
262
|
+
if format is not None:
|
|
263
|
+
params.append(("format", format))
|
|
264
|
+
if search is not None:
|
|
265
|
+
params.append(("search", search))
|
|
266
|
+
if folder_id is not None:
|
|
267
|
+
params.append(("folderId", folder_id))
|
|
268
|
+
|
|
269
|
+
query = f"?{urlencode(params)}" if params else ""
|
|
270
|
+
if project_id:
|
|
271
|
+
return f"/assets/projects/{quote(project_id, safe='')}{query}"
|
|
272
|
+
return f"/assets{query}"
|
|
273
|
+
|
|
274
|
+
|
|
275
|
+
def map_paginated_images(res: Dict[str, Any], *, fallback_page: int = 1, fallback_limit: int = 20) -> PaginatedImages:
|
|
276
|
+
"""Unwrap Express paginated assets payload into PaginatedImages."""
|
|
277
|
+
data_field = res.get("data")
|
|
278
|
+
if isinstance(data_field, list):
|
|
279
|
+
raw_items = data_field
|
|
280
|
+
pag = res.get("pagination") or {}
|
|
281
|
+
elif isinstance(data_field, dict):
|
|
282
|
+
raw_items = data_field.get("data") if isinstance(data_field.get("data"), list) else (
|
|
283
|
+
data_field.get("assets") if isinstance(data_field.get("assets"), list) else []
|
|
284
|
+
)
|
|
285
|
+
pag = data_field.get("pagination") or res.get("pagination") or {}
|
|
286
|
+
else:
|
|
287
|
+
raw_items = []
|
|
288
|
+
pag = res.get("pagination") or {}
|
|
289
|
+
|
|
290
|
+
return {
|
|
291
|
+
"data": [map_image_asset(item) for item in raw_items if isinstance(item, dict)],
|
|
292
|
+
"pagination": {
|
|
293
|
+
"total": int(pag.get("total", len(raw_items))),
|
|
294
|
+
"page": int(pag.get("page", fallback_page)),
|
|
295
|
+
"pageSize": int(pag.get("limit") or pag.get("page_size") or pag.get("pageSize") or fallback_limit),
|
|
296
|
+
"totalPages": pag.get("totalPages") if pag.get("totalPages") is not None else pag.get("total_pages"),
|
|
297
|
+
"hasNext": bool(pag.get("hasNext") if pag.get("hasNext") is not None else pag.get("has_next", False)),
|
|
298
|
+
"hasPrev": bool(pag.get("hasPrev") if pag.get("hasPrev") is not None else pag.get("has_prev", False)),
|
|
299
|
+
},
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
|
|
303
|
+
def map_delete_result(res: Dict[str, Any], requested_id: str) -> DeleteResult:
|
|
304
|
+
data = res.get("data") if isinstance(res.get("data"), dict) else {}
|
|
305
|
+
return {
|
|
306
|
+
"success": True,
|
|
307
|
+
"id": str(data.get("assetId") or data.get("id") or requested_id),
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def map_usage_summary(res: Dict[str, Any]) -> UsageSummary:
|
|
312
|
+
d = res.get("data") if isinstance(res.get("data"), dict) else {}
|
|
313
|
+
ready = int(d.get("total_ready_images") or 0)
|
|
314
|
+
quota = d.get("storage_quota_bytes")
|
|
315
|
+
remaining = d.get("remaining_storage_bytes")
|
|
316
|
+
pct = d.get("storage_quota_used_percentage")
|
|
317
|
+
if pct is None:
|
|
318
|
+
pct = d.get("percentage_used")
|
|
319
|
+
|
|
320
|
+
return {
|
|
321
|
+
"totalStoredBytes": int(d.get("total_stored_bytes") if d.get("total_stored_bytes") is not None else d.get("storage_bytes", 0)),
|
|
322
|
+
"totalReadyImages": ready,
|
|
323
|
+
"successfulUploads": int(d.get("successful_uploads") if d.get("successful_uploads") is not None else ready),
|
|
324
|
+
"deletedImages": int(d.get("deleted_images") or 0),
|
|
325
|
+
"storageQuotaBytes": int(quota) if quota is not None else None,
|
|
326
|
+
"storageQuotaUsedPercentage": float(pct) if pct is not None else None,
|
|
327
|
+
"remainingStorageBytes": int(remaining) if remaining is not None else None,
|
|
328
|
+
}
|
bigbucket/client.py
ADDED
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
"""Main synchronous and asynchronous BigBucket SDK clients."""
|
|
2
|
+
|
|
3
|
+
import os
|
|
4
|
+
from typing import Optional
|
|
5
|
+
from urllib.parse import quote
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from ._normalize import map_image_asset, resolve_file_data
|
|
10
|
+
from .resources.images import AsyncImagesResource, ImagesResource
|
|
11
|
+
from .resources.uploads import AsyncUploadsResource, UploadsResource
|
|
12
|
+
from .resources.usage import AsyncUsageResource, UsageResource
|
|
13
|
+
from .transform import build_transform_url
|
|
14
|
+
from .transport import AsyncTransport, SyncTransport
|
|
15
|
+
from .types import (
|
|
16
|
+
FileInput,
|
|
17
|
+
ImageAsset,
|
|
18
|
+
TransformFit,
|
|
19
|
+
TransformFormat,
|
|
20
|
+
UploadMode,
|
|
21
|
+
)
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def _resolve_api_key(api_key: Optional[str]) -> str:
|
|
25
|
+
resolved = api_key if api_key is not None else os.environ.get("BIGBUCKET_API_KEY", "")
|
|
26
|
+
if not resolved or not resolved.strip():
|
|
27
|
+
raise ValueError(
|
|
28
|
+
"A valid BigBucket API key is required (e.g. bb_sec_...). "
|
|
29
|
+
"Pass api_key=... or set the BIGBUCKET_API_KEY environment variable."
|
|
30
|
+
)
|
|
31
|
+
return resolved
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class BigBucket:
|
|
35
|
+
"""Synchronous BigBucket SDK client for Flask, Django, and Python services."""
|
|
36
|
+
|
|
37
|
+
def __init__(
|
|
38
|
+
self,
|
|
39
|
+
api_key: Optional[str] = None,
|
|
40
|
+
*,
|
|
41
|
+
base_url: Optional[str] = None,
|
|
42
|
+
timeout: float = 30.0,
|
|
43
|
+
http_client: Optional[httpx.Client] = None,
|
|
44
|
+
transport: Optional[httpx.BaseTransport] = None,
|
|
45
|
+
) -> None:
|
|
46
|
+
key = _resolve_api_key(api_key)
|
|
47
|
+
self._transport = SyncTransport(
|
|
48
|
+
api_key=key,
|
|
49
|
+
base_url=base_url,
|
|
50
|
+
timeout=timeout,
|
|
51
|
+
http_client=http_client,
|
|
52
|
+
transport=transport,
|
|
53
|
+
)
|
|
54
|
+
self.images = ImagesResource(self._transport)
|
|
55
|
+
self.uploads = UploadsResource(self._transport)
|
|
56
|
+
self.usage = UsageResource(self._transport)
|
|
57
|
+
|
|
58
|
+
def __enter__(self) -> "BigBucket":
|
|
59
|
+
return self
|
|
60
|
+
|
|
61
|
+
def __exit__(self, *_: object) -> None:
|
|
62
|
+
self.close()
|
|
63
|
+
|
|
64
|
+
def close(self) -> None:
|
|
65
|
+
"""Close the underlying httpx Client connection pool."""
|
|
66
|
+
self._transport.close()
|
|
67
|
+
|
|
68
|
+
def upload(
|
|
69
|
+
self,
|
|
70
|
+
file: FileInput,
|
|
71
|
+
*,
|
|
72
|
+
filename: Optional[str] = None,
|
|
73
|
+
content_type: Optional[str] = None,
|
|
74
|
+
file_size: Optional[int] = None,
|
|
75
|
+
folder_id: Optional[str] = None,
|
|
76
|
+
upload_mode: Optional[UploadMode] = None,
|
|
77
|
+
poll_interval: float = 0.5,
|
|
78
|
+
poll_timeout: float = 30.0,
|
|
79
|
+
) -> ImageAsset:
|
|
80
|
+
"""Upload an image end-to-end (intent -> R2 PUT or Gateway -> complete -> poll)."""
|
|
81
|
+
raw_bytes, resolved_name, resolved_mime, resolved_size = resolve_file_data(
|
|
82
|
+
file,
|
|
83
|
+
filename=filename,
|
|
84
|
+
content_type=content_type,
|
|
85
|
+
file_size=file_size,
|
|
86
|
+
)
|
|
87
|
+
|
|
88
|
+
session = self.uploads.create(
|
|
89
|
+
filename=resolved_name,
|
|
90
|
+
content_type=resolved_mime,
|
|
91
|
+
file_size=resolved_size,
|
|
92
|
+
folder_id=folder_id,
|
|
93
|
+
upload_mode=upload_mode,
|
|
94
|
+
)
|
|
95
|
+
|
|
96
|
+
if session["mode"] == "GATEWAY":
|
|
97
|
+
gateway_res = self._transport.request(
|
|
98
|
+
"POST",
|
|
99
|
+
f"/uploads/gateway/{quote(session['uploadSessionId'], safe='')}",
|
|
100
|
+
files={"file": (resolved_name, raw_bytes, resolved_mime)},
|
|
101
|
+
)
|
|
102
|
+
gateway_data = gateway_res.get("data") if isinstance(gateway_res, dict) else None
|
|
103
|
+
if isinstance(gateway_data, dict) and isinstance(gateway_data.get("asset"), dict):
|
|
104
|
+
return map_image_asset(gateway_data["asset"])
|
|
105
|
+
return self.uploads.wait_for_completion(
|
|
106
|
+
session["uploadSessionId"],
|
|
107
|
+
poll_interval=poll_interval,
|
|
108
|
+
poll_timeout=poll_timeout,
|
|
109
|
+
)
|
|
110
|
+
|
|
111
|
+
self._transport.upload_to_presigned_url(
|
|
112
|
+
session["presigned"]["url"],
|
|
113
|
+
session["presigned"]["method"],
|
|
114
|
+
session["presigned"]["headers"],
|
|
115
|
+
raw_bytes,
|
|
116
|
+
)
|
|
117
|
+
|
|
118
|
+
return self.uploads.complete(
|
|
119
|
+
session["uploadSessionId"],
|
|
120
|
+
poll_interval=poll_interval,
|
|
121
|
+
poll_timeout=poll_timeout,
|
|
122
|
+
)
|
|
123
|
+
|
|
124
|
+
def transform_url(
|
|
125
|
+
self,
|
|
126
|
+
base_url: str,
|
|
127
|
+
*,
|
|
128
|
+
width: Optional[int] = None,
|
|
129
|
+
w: Optional[int] = None,
|
|
130
|
+
height: Optional[int] = None,
|
|
131
|
+
h: Optional[int] = None,
|
|
132
|
+
quality: Optional[int] = None,
|
|
133
|
+
q: Optional[int] = None,
|
|
134
|
+
fit: Optional[TransformFit] = None,
|
|
135
|
+
format: Optional[TransformFormat] = None,
|
|
136
|
+
fmt: Optional[TransformFormat] = None,
|
|
137
|
+
f: Optional[TransformFormat] = None,
|
|
138
|
+
) -> str:
|
|
139
|
+
"""Generate a canonical Sharp CDN transformation URL (w, h, q, fit, fmt)."""
|
|
140
|
+
return build_transform_url(
|
|
141
|
+
base_url,
|
|
142
|
+
width=width,
|
|
143
|
+
w=w,
|
|
144
|
+
height=height,
|
|
145
|
+
h=h,
|
|
146
|
+
quality=quality,
|
|
147
|
+
q=q,
|
|
148
|
+
fit=fit,
|
|
149
|
+
format=format,
|
|
150
|
+
fmt=fmt,
|
|
151
|
+
f=f,
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
|
|
155
|
+
class AsyncBigBucket:
|
|
156
|
+
"""Asynchronous BigBucket SDK client for FastAPI and asyncio applications."""
|
|
157
|
+
|
|
158
|
+
def __init__(
|
|
159
|
+
self,
|
|
160
|
+
api_key: Optional[str] = None,
|
|
161
|
+
*,
|
|
162
|
+
base_url: Optional[str] = None,
|
|
163
|
+
timeout: float = 30.0,
|
|
164
|
+
http_client: Optional[httpx.AsyncClient] = None,
|
|
165
|
+
transport: Optional[httpx.AsyncBaseTransport] = None,
|
|
166
|
+
) -> None:
|
|
167
|
+
key = _resolve_api_key(api_key)
|
|
168
|
+
self._transport = AsyncTransport(
|
|
169
|
+
api_key=key,
|
|
170
|
+
base_url=base_url,
|
|
171
|
+
timeout=timeout,
|
|
172
|
+
http_client=http_client,
|
|
173
|
+
transport=transport,
|
|
174
|
+
)
|
|
175
|
+
self.images = AsyncImagesResource(self._transport)
|
|
176
|
+
self.uploads = AsyncUploadsResource(self._transport)
|
|
177
|
+
self.usage = AsyncUsageResource(self._transport)
|
|
178
|
+
|
|
179
|
+
async def __aenter__(self) -> "AsyncBigBucket":
|
|
180
|
+
return self
|
|
181
|
+
|
|
182
|
+
async def __aexit__(self, *_: object) -> None:
|
|
183
|
+
await self.aclose()
|
|
184
|
+
|
|
185
|
+
async def aclose(self) -> None:
|
|
186
|
+
"""Close the underlying httpx AsyncClient connection pool."""
|
|
187
|
+
await self._transport.aclose()
|
|
188
|
+
|
|
189
|
+
async def upload(
|
|
190
|
+
self,
|
|
191
|
+
file: FileInput,
|
|
192
|
+
*,
|
|
193
|
+
filename: Optional[str] = None,
|
|
194
|
+
content_type: Optional[str] = None,
|
|
195
|
+
file_size: Optional[int] = None,
|
|
196
|
+
folder_id: Optional[str] = None,
|
|
197
|
+
upload_mode: Optional[UploadMode] = None,
|
|
198
|
+
poll_interval: float = 0.5,
|
|
199
|
+
poll_timeout: float = 30.0,
|
|
200
|
+
) -> ImageAsset:
|
|
201
|
+
"""Upload an image asynchronously end-to-end."""
|
|
202
|
+
raw_bytes, resolved_name, resolved_mime, resolved_size = resolve_file_data(
|
|
203
|
+
file,
|
|
204
|
+
filename=filename,
|
|
205
|
+
content_type=content_type,
|
|
206
|
+
file_size=file_size,
|
|
207
|
+
)
|
|
208
|
+
|
|
209
|
+
session = await self.uploads.create(
|
|
210
|
+
filename=resolved_name,
|
|
211
|
+
content_type=resolved_mime,
|
|
212
|
+
file_size=resolved_size,
|
|
213
|
+
folder_id=folder_id,
|
|
214
|
+
upload_mode=upload_mode,
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
if session["mode"] == "GATEWAY":
|
|
218
|
+
gateway_res = await self._transport.request(
|
|
219
|
+
"POST",
|
|
220
|
+
f"/uploads/gateway/{quote(session['uploadSessionId'], safe='')}",
|
|
221
|
+
files={"file": (resolved_name, raw_bytes, resolved_mime)},
|
|
222
|
+
)
|
|
223
|
+
gateway_data = gateway_res.get("data") if isinstance(gateway_res, dict) else None
|
|
224
|
+
if isinstance(gateway_data, dict) and isinstance(gateway_data.get("asset"), dict):
|
|
225
|
+
return map_image_asset(gateway_data["asset"])
|
|
226
|
+
return await self.uploads.wait_for_completion(
|
|
227
|
+
session["uploadSessionId"],
|
|
228
|
+
poll_interval=poll_interval,
|
|
229
|
+
poll_timeout=poll_timeout,
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
await self._transport.upload_to_presigned_url(
|
|
233
|
+
session["presigned"]["url"],
|
|
234
|
+
session["presigned"]["method"],
|
|
235
|
+
session["presigned"]["headers"],
|
|
236
|
+
raw_bytes,
|
|
237
|
+
)
|
|
238
|
+
|
|
239
|
+
return await self.uploads.complete(
|
|
240
|
+
session["uploadSessionId"],
|
|
241
|
+
poll_interval=poll_interval,
|
|
242
|
+
poll_timeout=poll_timeout,
|
|
243
|
+
)
|
|
244
|
+
|
|
245
|
+
def transform_url(
|
|
246
|
+
self,
|
|
247
|
+
base_url: str,
|
|
248
|
+
*,
|
|
249
|
+
width: Optional[int] = None,
|
|
250
|
+
w: Optional[int] = None,
|
|
251
|
+
height: Optional[int] = None,
|
|
252
|
+
h: Optional[int] = None,
|
|
253
|
+
quality: Optional[int] = None,
|
|
254
|
+
q: Optional[int] = None,
|
|
255
|
+
fit: Optional[TransformFit] = None,
|
|
256
|
+
format: Optional[TransformFormat] = None,
|
|
257
|
+
fmt: Optional[TransformFormat] = None,
|
|
258
|
+
f: Optional[TransformFormat] = None,
|
|
259
|
+
) -> str:
|
|
260
|
+
"""Generate a canonical Sharp CDN transformation URL (w, h, q, fit, fmt)."""
|
|
261
|
+
return build_transform_url(
|
|
262
|
+
base_url,
|
|
263
|
+
width=width,
|
|
264
|
+
w=w,
|
|
265
|
+
height=height,
|
|
266
|
+
h=h,
|
|
267
|
+
quality=quality,
|
|
268
|
+
q=q,
|
|
269
|
+
fit=fit,
|
|
270
|
+
format=format,
|
|
271
|
+
fmt=fmt,
|
|
272
|
+
f=f,
|
|
273
|
+
)
|