Debian Codegraph @

docs/source/guide/s3-example-creating-buckets.rst

raw
1 .. Copyright 2010-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.
2
3 This work is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike 4.0
4 International License (the "License"). You may not use this file except in compliance with the
5 License. A copy of the License is located at http://creativecommons.org/licenses/by-nc-sa/4.0/.
6
7 This file is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND,
8 either express or implied. See the License for the specific language governing permissions and
9 limitations under the License.
10
11
12 #################
13 Amazon S3 buckets
14 #################
15
16 An Amazon S3 bucket is a storage location to hold files. S3 files are referred
17 to as objects.
18
19 This section describes how to use the AWS SDK for Python to perform common
20 operations on S3 buckets.
21
22
23 Create an Amazon S3 bucket
24 ==========================
25
26 The name of an Amazon S3 bucket must be unique across all regions of the AWS
27 platform. The bucket can be located in a specific region to minimize latency
28 or to address regulatory requirements.
29
30 .. note::
31 The ``LocationConstraint`` value is used to specify the region where a bucket
32 will be created. S3 requires ``LocationConstraint`` to be specified when creating
33 buckets using a client in regions other than ``us-east-1``. When no region is
34 specified, ``us-east-1`` is used by default. The example below ensures the S3
35 client is created in the same region as the bucket to avoid a
36 ``IllegalLocationConstraintException`` error.
37
38 .. code-block:: python
39
40 import logging
41 import boto3
42 from botocore.exceptions import ClientError
43
44
45 def create_bucket(bucket_name, region='us-east-1'):
46 """Create an S3 bucket in a specified region
47
48 If a region is not specified, the bucket is created in the S3 default
49 region (us-east-1).
50
51 :param bucket_name: Bucket to create
52 :param region: String region to create bucket in, e.g., 'us-west-2'
53 :return: True if bucket created, else False
54 """
55
56 # Create bucket
57 try:
58 bucket_config = {}
59 s3_client = boto3.client('s3', region_name=region)
60 if region != 'us-east-1':
61 bucket_config['CreateBucketConfiguration'] = {'LocationConstraint': region}
62
63 s3_client.create_bucket(Bucket=bucket_name, **bucket_config)
64 except ClientError as e:
65 logging.error(e)
66 return False
67 return True
68
69 List existing buckets
70 =====================
71
72 List all the existing buckets for the AWS account.
73
74 .. code-block:: python
75
76 # Retrieve the list of existing buckets
77 s3 = boto3.client('s3')
78 response = s3.list_buckets()
79
80 # Output the bucket names
81 print('Existing buckets:')
82 for bucket in response['Buckets']:
83 print(f' {bucket["Name"]}')