O'Reilly logo

Python and AWS Cookbook by Mitch Garnaat

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 3. S3 Recipes

Create a Bucket

Problem

Before you can store anything in S3, you need to first create a bucket to contain the objects.

Solution

Use the create_bucket method to create a new bucket.

Discussion

Example 3-1 shows a function that takes the name of the bucket you want to create as a parameter. It will then try to create that bucket. If the bucket already exists, it will print an error.

Example 3-1. Create a Bucket
import boto

def create_bucket(bucket_name):
    """
    Create a bucket.  If the bucket already exists and you have
    access to it, no error will be returned by AWS.
    Note that bucket names are global to S3
    so you need to choose a unique name.
    """
    s3 = boto.connect_s3()

    # First let's see if we already have a bucket of this name.
    # The lookup method will return a Bucket object if the
    # bucket exists and we have access to it or None.
    bucket = s3.lookup(bucket_name)
    if bucket:
        print 'Bucket (%s) already exists' % bucket_name
    else:
        # Let's try to create the bucket.  This will fail if
        # the bucket has already been created by someone else.
        try:
            bucket = s3.create_bucket(bucket_name)
        except s3.provider.storage_create_error, e:
            print 'Bucket (%s) is owned by another user' % bucket_name
    return bucket

Create a Bucket in a Specific Location

Problem

You want to create a bucket in a specific geographic location.

Solution

Use the location parameter to the create_bucket method to specify the location of the new bucket.

Discussion

Originally, there was just a single S3 endpoint and all data was ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required