-
Notifications
You must be signed in to change notification settings - Fork 309
/
api.py
3219 lines (2895 loc) · 114 KB
/
api.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# MinIO Python Library for Amazon S3 Compatible Cloud Storage, (C)
# 2015, 2016, 2017 MinIO, Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# pylint: disable=too-many-arguments
# pylint: disable=too-many-branches
# pylint: disable=too-many-function-args
# pylint: disable=too-many-lines
# pylint: disable=too-many-public-methods
# pylint: disable=too-many-statements
"""
Simple Storage Service (aka S3) client to perform bucket and object operations.
"""
from __future__ import absolute_import, annotations
import itertools
import os
import tarfile
from datetime import datetime, timedelta
from io import BytesIO
from random import random
from typing import IO, BinaryIO, Iterator, TextIO, Tuple, Union, cast
from urllib.parse import urlunsplit
from xml.etree import ElementTree as ET
import certifi
import urllib3
from urllib3 import Retry
from urllib3._collections import HTTPHeaderDict
from urllib3.response import BaseHTTPResponse
from urllib3.util import Timeout
from . import __title__, __version__, time
from .commonconfig import (COPY, REPLACE, ComposeSource, CopySource,
SnowballObject, Tags)
from .credentials import Credentials, StaticProvider
from .credentials.providers import Provider
from .datatypes import (Bucket, CompleteMultipartUploadResult, EventIterable,
ListAllMyBucketsResult, ListMultipartUploadsResult,
ListPartsResult, Object, Part, PostPolicy,
parse_copy_object, parse_list_objects)
from .deleteobjects import (DeleteError, DeleteObject, DeleteRequest,
DeleteResult)
from .error import InvalidResponseError, S3Error, ServerError
from .helpers import (_DEFAULT_USER_AGENT, MAX_MULTIPART_COUNT,
MAX_MULTIPART_OBJECT_SIZE, MAX_PART_SIZE, MIN_PART_SIZE,
BaseURL, DictType, ObjectWriteResult, ProgressType,
ThreadPool, check_bucket_name, check_non_empty_string,
check_sse, check_ssec, genheaders, get_part_info,
headers_to_strings, is_valid_policy_type, makedirs,
md5sum_hash, queryencode, read_part_data, sha256_hash)
from .legalhold import LegalHold
from .lifecycleconfig import LifecycleConfig
from .notificationconfig import NotificationConfig
from .objectlockconfig import ObjectLockConfig
from .replicationconfig import ReplicationConfig
from .retention import Retention
from .select import SelectObjectReader, SelectRequest
from .signer import presign_v4, sign_v4_s3
from .sse import Sse, SseCustomerKey
from .sseconfig import SSEConfig
from .tagging import Tagging
from .versioningconfig import VersioningConfig
from .xml import Element, SubElement, findtext, getbytes, marshal, unmarshal
class Minio:
"""
Simple Storage Service (aka S3) client to perform bucket and object
operations.
:param endpoint: Hostname of a S3 service.
:param access_key: Access key (aka user ID) of your account in S3 service.
:param secret_key: Secret Key (aka password) of your account in S3 service.
:param session_token: Session token of your account in S3 service.
:param secure: Flag to indicate to use secure (TLS) connection to S3
service or not.
:param region: Region name of buckets in S3 service.
:param http_client: Customized HTTP client.
:param credentials: Credentials provider of your account in S3 service.
:param cert_check: Flag to indicate to verify SSL certificate or not.
:return: :class:`Minio <Minio>` object
Example::
# Create client with anonymous access.
client = Minio("play.min.io")
# Create client with access and secret key.
client = Minio("s3.amazonaws.com", "ACCESS-KEY", "SECRET-KEY")
# Create client with access key and secret key with specific region.
client = Minio(
"play.minio.io:9000",
access_key="Q3AM3UQ867SPQQA43P2F",
secret_key="zuf+tfteSlswRu7BJ86wekitnifILbZam1KYY3TG",
region="my-region",
)
**NOTE on concurrent usage:** `Minio` object is thread safe when using
the Python `threading` library. Specifically, it is **NOT** safe to share
it between multiple processes, for example when using
`multiprocessing.Pool`. The solution is simply to create a new `Minio`
object in each process, and not share it between processes.
"""
_region_map: dict[str, str]
_base_url: BaseURL
_user_agent: str
_trace_stream: TextIO | None
_provider: Provider | None
_http: urllib3.PoolManager
def __init__(
self,
endpoint: str,
access_key: str | None = None,
secret_key: str | None = None,
session_token: str | None = None,
secure: bool = True,
region: str | None = None,
http_client: urllib3.PoolManager | None = None,
credentials: Provider | None = None,
cert_check: bool = True,
):
# Validate http client has correct base class.
if http_client and not isinstance(http_client, urllib3.PoolManager):
raise ValueError(
"HTTP client should be instance of `urllib3.PoolManager`"
)
self._region_map = {}
self._base_url = BaseURL(
("https://" if secure else "http://") + endpoint,
region,
)
self._user_agent = _DEFAULT_USER_AGENT
self._trace_stream = None
if access_key:
if secret_key is None:
raise ValueError("secret key must be provided with access key")
credentials = StaticProvider(access_key, secret_key, session_token)
self._provider = credentials
# Load CA certificates from SSL_CERT_FILE file if set
timeout = timedelta(minutes=5).seconds
self._http = http_client or urllib3.PoolManager(
timeout=Timeout(connect=timeout, read=timeout),
maxsize=10,
cert_reqs='CERT_REQUIRED' if cert_check else 'CERT_NONE',
ca_certs=os.environ.get('SSL_CERT_FILE') or certifi.where(),
retries=Retry(
total=5,
backoff_factor=0.2,
status_forcelist=[500, 502, 503, 504]
)
)
def __del__(self):
if hasattr(self, "_http"): # Only required for unit test run
self._http.clear()
def _handle_redirect_response(
self,
method: str,
bucket_name: str | None,
response: BaseHTTPResponse,
retry: bool = False,
) -> tuple[str | None, str | None]:
"""
Handle redirect response indicates whether retry HEAD request
on failure.
"""
code, message = {
301: ("PermanentRedirect", "Moved Permanently"),
307: ("Redirect", "Temporary redirect"),
400: ("BadRequest", "Bad request"),
}.get(response.status, (None, None))
region = response.headers.get("x-amz-bucket-region")
if message and region:
message += "; use region " + region
if (
retry and region and method == "HEAD" and bucket_name and
self._region_map.get(bucket_name)
):
code, message = ("RetryHead", None)
return code, message
def _build_headers(
self,
host: str,
headers: DictType | None,
body: bytes | None,
creds: Credentials | None,
) -> tuple[DictType, datetime]:
"""Build headers with given parameters."""
headers = headers or {}
md5sum_added = headers.get("Content-MD5")
headers["Host"] = host
headers["User-Agent"] = self._user_agent
sha256 = None
md5sum = None
if body:
headers["Content-Length"] = str(len(body))
if creds:
if self._base_url.is_https:
sha256 = "UNSIGNED-PAYLOAD"
md5sum = None if md5sum_added else md5sum_hash(body)
else:
sha256 = sha256_hash(body)
else:
md5sum = None if md5sum_added else md5sum_hash(body)
if md5sum:
headers["Content-MD5"] = md5sum
if sha256:
headers["x-amz-content-sha256"] = sha256
if creds and creds.session_token:
headers["X-Amz-Security-Token"] = creds.session_token
date = time.utcnow()
headers["x-amz-date"] = time.to_amz_date(date)
return headers, date
def _url_open(
self,
method: str,
region: str,
bucket_name: str | None = None,
object_name: str | None = None,
body: bytes | None = None,
headers: DictType | None = None,
query_params: DictType | None = None,
preload_content: bool = True,
no_body_trace: bool = False,
) -> BaseHTTPResponse:
"""Execute HTTP request."""
creds = self._provider.retrieve() if self._provider else None
url = self._base_url.build(
method,
region,
bucket_name=bucket_name,
object_name=object_name,
query_params=query_params,
)
headers, date = self._build_headers(url.netloc, headers, body, creds)
if creds:
headers = sign_v4_s3(
method,
url,
region,
headers,
creds,
cast(str, headers.get("x-amz-content-sha256")),
date,
)
if self._trace_stream:
self._trace_stream.write("---------START-HTTP---------\n")
query = ("?" + url.query) if url.query else ""
self._trace_stream.write(f"{method} {url.path}{query} HTTP/1.1\n")
self._trace_stream.write(
headers_to_strings(headers, titled_key=True),
)
self._trace_stream.write("\n")
if not no_body_trace and body is not None:
self._trace_stream.write("\n")
self._trace_stream.write(
body.decode() if isinstance(body, bytes) else str(body),
)
self._trace_stream.write("\n")
self._trace_stream.write("\n")
http_headers = HTTPHeaderDict()
for key, value in (headers or {}).items():
if isinstance(value, (list, tuple)):
for val in value:
http_headers.add(key, val)
else:
http_headers.add(key, value)
response = self._http.urlopen(
method,
urlunsplit(url),
body=body,
headers=http_headers,
preload_content=preload_content,
)
if self._trace_stream:
self._trace_stream.write(f"HTTP/1.1 {response.status}\n")
self._trace_stream.write(
headers_to_strings(response.headers),
)
self._trace_stream.write("\n")
if response.status in [200, 204, 206]:
if self._trace_stream:
if preload_content:
self._trace_stream.write("\n")
self._trace_stream.write(response.data.decode())
self._trace_stream.write("\n")
self._trace_stream.write("----------END-HTTP----------\n")
return response
response.read(cache_content=True)
if not preload_content:
response.release_conn()
if self._trace_stream and method != "HEAD" and response.data:
self._trace_stream.write(response.data.decode())
self._trace_stream.write("\n")
if (
method != "HEAD" and
"application/xml" not in response.headers.get(
"content-type", "",
).split(";")
):
if self._trace_stream:
self._trace_stream.write("----------END-HTTP----------\n")
if response.status == 304 and not response.data:
raise ServerError(
f"server failed with HTTP status code {response.status}",
response.status,
)
raise InvalidResponseError(
response.status,
cast(str, response.headers.get("content-type")),
response.data.decode() if response.data else None,
)
if not response.data and method != "HEAD":
if self._trace_stream:
self._trace_stream.write("----------END-HTTP----------\n")
raise InvalidResponseError(
response.status,
response.headers.get("content-type"),
None,
)
response_error = S3Error.fromxml(response) if response.data else None
if self._trace_stream:
self._trace_stream.write("----------END-HTTP----------\n")
error_map = {
301: lambda: self._handle_redirect_response(
method, bucket_name, response, True,
),
307: lambda: self._handle_redirect_response(
method, bucket_name, response, True,
),
400: lambda: self._handle_redirect_response(
method, bucket_name, response, True,
),
403: lambda: ("AccessDenied", "Access denied"),
404: lambda: (
("NoSuchKey", "Object does not exist")
if object_name
else ("NoSuchBucket", "Bucket does not exist")
if bucket_name
else ("ResourceNotFound", "Request resource not found")
),
405: lambda: (
"MethodNotAllowed",
"The specified method is not allowed against this resource",
),
409: lambda: (
("NoSuchBucket", "Bucket does not exist")
if bucket_name
else ("ResourceConflict", "Request resource conflicts"),
),
501: lambda: (
"MethodNotAllowed",
"The specified method is not allowed against this resource",
),
}
if not response_error:
func = error_map.get(response.status)
code, message = func() if func else (None, None)
if not code:
raise ServerError(
f"server failed with HTTP status code {response.status}",
response.status,
)
response_error = S3Error(
cast(str, code),
cast(Union[str, None], message),
url.path,
response.headers.get("x-amz-request-id"),
response.headers.get("x-amz-id-2"),
response,
bucket_name=bucket_name,
object_name=object_name,
)
if response_error.code in ["NoSuchBucket", "RetryHead"]:
if bucket_name is not None:
self._region_map.pop(bucket_name, None)
raise response_error
def _execute(
self,
method: str,
bucket_name: str | None = None,
object_name: str | None = None,
body: bytes | None = None,
headers: DictType | None = None,
query_params: DictType | None = None,
preload_content: bool = True,
no_body_trace: bool = False,
) -> BaseHTTPResponse:
"""Execute HTTP request."""
region = self._get_region(bucket_name)
try:
return self._url_open(
method,
region,
bucket_name=bucket_name,
object_name=object_name,
body=body,
headers=headers,
query_params=query_params,
preload_content=preload_content,
no_body_trace=no_body_trace,
)
except S3Error as exc:
if exc.code != "RetryHead":
raise
# Retry only once on RetryHead error.
try:
return self._url_open(
method,
region,
bucket_name=bucket_name,
object_name=object_name,
body=body,
headers=headers,
query_params=query_params,
preload_content=preload_content,
no_body_trace=no_body_trace,
)
except S3Error as exc:
if exc.code != "RetryHead":
raise
code, message = self._handle_redirect_response(
method, bucket_name, exc.response,
)
raise exc.copy(cast(str, code), cast(str, message))
def _get_region(self, bucket_name: str | None) -> str:
"""
Return region of given bucket either from region cache or set in
constructor.
"""
if self._base_url.region:
return self._base_url.region
if not bucket_name or not self._provider:
return "us-east-1"
region = self._region_map.get(bucket_name)
if region:
return region
# Execute GetBucketLocation REST API to get region of the bucket.
response = self._url_open(
"GET",
"us-east-1",
bucket_name=bucket_name,
query_params={"location": ""},
)
element = ET.fromstring(response.data.decode())
if not element.text:
region = "us-east-1"
elif element.text == "EU" and self._base_url.is_aws_host:
region = "eu-west-1"
else:
region = element.text
self._region_map[bucket_name] = region
return region
def set_app_info(self, app_name: str, app_version: str):
"""
Set your application name and version to user agent header.
:param app_name: Application name.
:param app_version: Application version.
Example::
client.set_app_info('my_app', '1.0.2')
"""
if not (app_name and app_version):
raise ValueError("Application name/version cannot be empty.")
self._user_agent = f"{_DEFAULT_USER_AGENT} {app_name}/{app_version}"
def trace_on(self, stream: TextIO):
"""
Enable http trace.
:param stream: Stream for writing HTTP call tracing.
"""
if not stream:
raise ValueError('Input stream for trace output is invalid.')
# Save new output stream.
self._trace_stream = stream
def trace_off(self):
"""
Disable HTTP trace.
"""
self._trace_stream = None
def enable_accelerate_endpoint(self):
"""Enables accelerate endpoint for Amazon S3 endpoint."""
self._base_url.accelerate_host_flag = True
def disable_accelerate_endpoint(self):
"""Disables accelerate endpoint for Amazon S3 endpoint."""
self._base_url.accelerate_host_flag = False
def enable_dualstack_endpoint(self):
"""Enables dualstack endpoint for Amazon S3 endpoint."""
self._base_url.dualstack_host_flag = True
def disable_dualstack_endpoint(self):
"""Disables dualstack endpoint for Amazon S3 endpoint."""
self._base_url.dualstack_host_flag = False
def enable_virtual_style_endpoint(self):
"""Enables virtual style endpoint."""
self._base_url.virtual_style_flag = True
def disable_virtual_style_endpoint(self):
"""Disables virtual style endpoint."""
self._base_url.virtual_style_flag = False
def select_object_content(
self,
bucket_name: str,
object_name: str,
request: SelectRequest,
) -> SelectObjectReader:
"""
Select content of an object by SQL expression.
:param bucket_name: Name of the bucket.
:param object_name: Object name in the bucket.
:param request: :class:`SelectRequest <SelectRequest>` object.
:return: A reader contains requested records and progress information.
Example::
with client.select_object_content(
"my-bucket",
"my-object.csv",
SelectRequest(
"select * from S3Object",
CSVInputSerialization(),
CSVOutputSerialization(),
request_progress=True,
),
) as result:
for data in result.stream():
print(data.decode())
print(result.stats())
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
check_non_empty_string(object_name)
if not isinstance(request, SelectRequest):
raise ValueError("request must be SelectRequest type")
body = marshal(request)
response = self._execute(
"POST",
bucket_name=bucket_name,
object_name=object_name,
body=body,
headers={"Content-MD5": cast(str, md5sum_hash(body))},
query_params={"select": "", "select-type": "2"},
preload_content=False,
)
return SelectObjectReader(response)
def make_bucket(
self,
bucket_name: str,
location: str | None = None,
object_lock: bool = False,
):
"""
Create a bucket with region and object lock.
:param bucket_name: Name of the bucket.
:param location: Region in which the bucket will be created.
:param object_lock: Flag to set object-lock feature.
Examples::
# Create bucket.
client.make_bucket("my-bucket")
# Create bucket on specific region.
client.make_bucket("my-bucket", "us-west-1")
# Create bucket with object-lock feature on specific region.
client.make_bucket("my-bucket", "eu-west-2", object_lock=True)
"""
check_bucket_name(bucket_name, True,
s3_check=self._base_url.is_aws_host)
if self._base_url.region:
# Error out if region does not match with region passed via
# constructor.
if location and self._base_url.region != location:
raise ValueError(
f"region must be {self._base_url.region}, "
f"but passed {location}"
)
location = self._base_url.region or location or "us-east-1"
headers: DictType | None = (
{"x-amz-bucket-object-lock-enabled": "true"}
if object_lock else None
)
body = None
if location != "us-east-1":
element = Element("CreateBucketConfiguration")
SubElement(element, "LocationConstraint", location)
body = getbytes(element)
self._url_open(
"PUT",
location,
bucket_name=bucket_name,
body=body,
headers=headers,
)
self._region_map[bucket_name] = location
def list_buckets(self) -> list[Bucket]:
"""
List information of all accessible buckets.
:return: List of :class:`Bucket <Bucket>` object.
Example::
buckets = client.list_buckets()
for bucket in buckets:
print(bucket.name, bucket.creation_date)
"""
response = self._execute("GET")
result = unmarshal(ListAllMyBucketsResult, response.data.decode())
return result.buckets
def bucket_exists(self, bucket_name: str) -> bool:
"""
Check if a bucket exists.
:param bucket_name: Name of the bucket.
:return: True if the bucket exists.
Example::
if client.bucket_exists("my-bucket"):
print("my-bucket exists")
else:
print("my-bucket does not exist")
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
try:
self._execute("HEAD", bucket_name)
return True
except S3Error as exc:
if exc.code != "NoSuchBucket":
raise
return False
def remove_bucket(self, bucket_name: str):
"""
Remove an empty bucket.
:param bucket_name: Name of the bucket.
Example::
client.remove_bucket("my-bucket")
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
self._execute("DELETE", bucket_name)
self._region_map.pop(bucket_name, None)
def get_bucket_policy(self, bucket_name: str) -> str:
"""
Get bucket policy configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: Bucket policy configuration as JSON string.
Example::
policy = client.get_bucket_policy("my-bucket")
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
response = self._execute(
"GET", bucket_name, query_params={"policy": ""},
)
return response.data.decode()
def delete_bucket_policy(self, bucket_name: str):
"""
Delete bucket policy configuration of a bucket.
:param bucket_name: Name of the bucket.
Example::
client.delete_bucket_policy("my-bucket")
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
self._execute("DELETE", bucket_name, query_params={"policy": ""})
def set_bucket_policy(self, bucket_name: str, policy: str | bytes):
"""
Set bucket policy configuration to a bucket.
:param bucket_name: Name of the bucket.
:param policy: Bucket policy configuration as JSON string.
Example::
client.set_bucket_policy("my-bucket", policy)
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
is_valid_policy_type(policy)
self._execute(
"PUT",
bucket_name,
body=policy if isinstance(policy, bytes) else policy.encode(),
headers={"Content-MD5": cast(str, md5sum_hash(policy))},
query_params={"policy": ""},
)
def get_bucket_notification(self, bucket_name: str) -> NotificationConfig:
"""
Get notification configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: :class:`NotificationConfig <NotificationConfig>` object.
Example::
config = client.get_bucket_notification("my-bucket")
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
response = self._execute(
"GET", bucket_name, query_params={"notification": ""},
)
return unmarshal(NotificationConfig, response.data.decode())
def set_bucket_notification(
self,
bucket_name: str,
config: NotificationConfig,
):
"""
Set notification configuration of a bucket.
:param bucket_name: Name of the bucket.
:param config: class:`NotificationConfig <NotificationConfig>` object.
Example::
config = NotificationConfig(
queue_config_list=[
QueueConfig(
"QUEUE-ARN-OF-THIS-BUCKET",
["s3:ObjectCreated:*"],
config_id="1",
prefix_filter_rule=PrefixFilterRule("abc"),
),
],
)
client.set_bucket_notification("my-bucket", config)
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
if not isinstance(config, NotificationConfig):
raise ValueError("config must be NotificationConfig type")
body = marshal(config)
self._execute(
"PUT",
bucket_name,
body=body,
headers={"Content-MD5": cast(str, md5sum_hash(body))},
query_params={"notification": ""},
)
def delete_bucket_notification(self, bucket_name: str):
"""
Delete notification configuration of a bucket. On success, S3 service
stops notification of events previously set of the bucket.
:param bucket_name: Name of the bucket.
Example::
client.delete_bucket_notification("my-bucket")
"""
self.set_bucket_notification(bucket_name, NotificationConfig())
def set_bucket_encryption(self, bucket_name: str, config: SSEConfig):
"""
Set encryption configuration of a bucket.
:param bucket_name: Name of the bucket.
:param config: :class:`SSEConfig <SSEConfig>` object.
Example::
client.set_bucket_encryption(
"my-bucket", SSEConfig(Rule.new_sse_s3_rule()),
)
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
if not isinstance(config, SSEConfig):
raise ValueError("config must be SSEConfig type")
body = marshal(config)
self._execute(
"PUT",
bucket_name,
body=body,
headers={"Content-MD5": cast(str, md5sum_hash(body))},
query_params={"encryption": ""},
)
def get_bucket_encryption(self, bucket_name: str) -> SSEConfig | None:
"""
Get encryption configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: :class:`SSEConfig <SSEConfig>` object.
Example::
config = client.get_bucket_encryption("my-bucket")
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
try:
response = self._execute(
"GET",
bucket_name,
query_params={"encryption": ""},
)
return unmarshal(SSEConfig, response.data.decode())
except S3Error as exc:
if exc.code != "ServerSideEncryptionConfigurationNotFoundError":
raise
return None
def delete_bucket_encryption(self, bucket_name: str):
"""
Delete encryption configuration of a bucket.
:param bucket_name: Name of the bucket.
Example::
client.delete_bucket_encryption("my-bucket")
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
try:
self._execute(
"DELETE",
bucket_name,
query_params={"encryption": ""},
)
except S3Error as exc:
if exc.code != "ServerSideEncryptionConfigurationNotFoundError":
raise
def listen_bucket_notification(
self,
bucket_name: str,
prefix: str = "",
suffix: str = "",
events: tuple[str, ...] = ('s3:ObjectCreated:*',
's3:ObjectRemoved:*',
's3:ObjectAccessed:*'),
) -> EventIterable:
"""
Listen events of object prefix and suffix of a bucket. Caller should
iterate returned iterator to read new events.
:param bucket_name: Name of the bucket.
:param prefix: Listen events of object starts with prefix.
:param suffix: Listen events of object ends with suffix.
:param events: Events to listen.
:return: Iterator of event records as :dict:.
Example::
with client.listen_bucket_notification(
"my-bucket",
prefix="my-prefix/",
events=["s3:ObjectCreated:*", "s3:ObjectRemoved:*"],
) as events:
for event in events:
print(event)
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
if self._base_url.is_aws_host:
raise ValueError(
"ListenBucketNotification API is not supported in Amazon S3",
)
return EventIterable(
lambda: self._execute(
"GET",
bucket_name,
query_params={
"prefix": prefix or "",
"suffix": suffix or "",
"events": cast(Tuple[str], events),
},
preload_content=False,
),
)
def set_bucket_versioning(
self,
bucket_name: str,
config: VersioningConfig,
):
"""
Set versioning configuration to a bucket.
:param bucket_name: Name of the bucket.
:param config: :class:`VersioningConfig <VersioningConfig>`.
Example::
client.set_bucket_versioning(
"my-bucket", VersioningConfig(ENABLED),
)
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
if not isinstance(config, VersioningConfig):
raise ValueError("config must be VersioningConfig type")
body = marshal(config)
self._execute(
"PUT",
bucket_name,
body=body,
headers={"Content-MD5": cast(str, md5sum_hash(body))},
query_params={"versioning": ""},
)
def get_bucket_versioning(self, bucket_name: str) -> VersioningConfig:
"""
Get versioning configuration of a bucket.
:param bucket_name: Name of the bucket.
:return: :class:`VersioningConfig <VersioningConfig>`.
Example::
config = client.get_bucket_versioning("my-bucket")
print(config.status)
"""
check_bucket_name(bucket_name, s3_check=self._base_url.is_aws_host)
response = self._execute(
"GET",
bucket_name,
query_params={"versioning": ""},
)
return unmarshal(VersioningConfig, response.data.decode())
def fput_object(
self,
bucket_name: str,
object_name: str,
file_path: str,
content_type: str = "application/octet-stream",
metadata: DictType | None = None,
sse: Sse | None = None,
progress: ProgressType | None = None,
part_size: int = 0,
num_parallel_uploads: int = 3,
tags: Tags | None = None,
retention: Retention | None = None,
legal_hold: bool = False,
) -> ObjectWriteResult:
"""
Uploads data from a file to an object in a bucket.