Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions python-boto3-aws-s3/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
# Python, Boto3, and AWS S3: Demystified

This folder contains the sample code for the Real Python tutorial [Python, Boto3, and AWS S3: Demystified](https://realpython.com/python-boto3-aws-s3/).

## Setup

You need Python 3.10 or later and an AWS account. Create and activate a virtual environment, then install the pinned dependencies:

```console
$ python -m venv venv/
$ source venv/bin/activate
(venv) $ python -m pip install -r requirements.txt
```

Boto3 reads your credentials from `~/.aws/credentials` and your default region from `~/.aws/config`. The tutorial's *Installation* section shows how to create an IAM user with an access key and fill in both files.

## Usage

- `helpers.py` contains the helper functions that you write throughout the tutorial, such as `create_bucket()`, `create_temp_file()`, and `delete_all_objects()`.
- `s3_tutorial.py` runs every step of the tutorial in order: it creates two buckets, uploads, downloads, copies, and deletes objects, sets an ACL, encryption, a storage class, and versioning, traverses your buckets and objects, and then deletes everything it created.

Run the walkthrough from this folder:

```console
(venv) $ python s3_tutorial.py
```

The script talks to your real AWS account. The buckets and objects only exist while it runs, but S3 bills you for the requests it makes. The script also writes three small text files into your current working directory.

The ACL step re-enables ACLs and removes the public access block on the first bucket, as the tutorial does. Treat this as a practice setup and don't apply it to buckets that you use for real data.
54 changes: 54 additions & 0 deletions python-boto3-aws-s3/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import uuid

import boto3

s3_resource = boto3.resource("s3")


def create_bucket_name(bucket_prefix):
# The generated bucket name must be between 3 and 63 chars long
return "".join([bucket_prefix, str(uuid.uuid4())])


def create_bucket(bucket_prefix, s3_connection):
session = boto3.session.Session()
current_region = session.region_name
bucket_name = create_bucket_name(bucket_prefix)
if current_region == "us-east-1":
bucket_response = s3_connection.create_bucket(Bucket=bucket_name)
else:
bucket_response = s3_connection.create_bucket(
Bucket=bucket_name,
CreateBucketConfiguration={"LocationConstraint": current_region},
)
print(bucket_name, current_region)
return bucket_name, bucket_response


def create_temp_file(size, file_name, file_content):
random_file_name = "".join([str(uuid.uuid4().hex[:6]), file_name])
with open(random_file_name, "w") as f:
f.write(str(file_content) * size)
return random_file_name


def copy_to_bucket(bucket_from_name, bucket_to_name, file_name):
copy_source = {"Bucket": bucket_from_name, "Key": file_name}
s3_resource.Object(bucket_to_name, file_name).copy(copy_source)


def enable_bucket_versioning(bucket_name):
bkt_versioning = s3_resource.BucketVersioning(bucket_name)
bkt_versioning.enable()
print(bkt_versioning.status)


def delete_all_objects(bucket_name):
res = []
bucket = s3_resource.Bucket(bucket_name)
for obj_version in bucket.object_versions.all():
res.append(
{"Key": obj_version.object_key, "VersionId": obj_version.id}
)
print(res)
bucket.delete_objects(Delete={"Objects": res})
1 change: 1 addition & 0 deletions python-boto3-aws-s3/requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
boto3==1.44.18
143 changes: 143 additions & 0 deletions python-boto3-aws-s3/s3_tutorial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,143 @@
"""Run every step of the tutorial in order against your AWS account.

The script creates two buckets, works with a few small objects, and then
deletes everything it created.
"""

import tempfile
from pathlib import Path

from helpers import (
copy_to_bucket,
create_bucket,
create_temp_file,
delete_all_objects,
enable_bucket_versioning,
s3_resource,
)

# Common Operations: Creating a Bucket
first_bucket_name, first_response = create_bucket(
bucket_prefix="firstpythonbucket",
s3_connection=s3_resource.meta.client,
)
print(first_response)
second_bucket_name, second_response = create_bucket(
bucket_prefix="secondpythonbucket", s3_connection=s3_resource
)
print(second_response)

# Naming Your Files
first_file_name = create_temp_file(300, "firstfile.txt", "f")

# Creating Bucket and Object Instances
first_bucket = s3_resource.Bucket(name=first_bucket_name)
first_object = s3_resource.Object(
bucket_name=first_bucket_name, key=first_file_name
)

# Understanding Sub-Resources
first_object_again = first_bucket.Object(first_file_name)
first_bucket_again = first_object.Bucket()

# Uploading a File (the tutorial shows three equivalent ways)
s3_resource.Object(first_bucket_name, first_file_name).upload_file(
Filename=first_file_name
)
first_object.upload_file(first_file_name)
s3_resource.Bucket(first_bucket_name).upload_file(
Filename=first_file_name, Key=first_file_name
)
s3_resource.meta.client.upload_file(
Filename=first_file_name, Bucket=first_bucket_name, Key=first_file_name
)

# Downloading a File (to your system's temporary directory)
s3_resource.Object(first_bucket_name, first_file_name).download_file(
str(Path(tempfile.gettempdir()) / first_file_name)
)

# Copying an Object Between Buckets
copy_to_bucket(first_bucket_name, second_bucket_name, first_file_name)

# Deleting an Object
s3_resource.Object(second_bucket_name, first_file_name).delete()

# Advanced Configurations: ACL (Access Control Lists)
# Practice setup only: re-enable ACLs and lift the public access block
s3_resource.meta.client.put_bucket_ownership_controls(
Bucket=first_bucket_name,
OwnershipControls={"Rules": [{"ObjectOwnership": "ObjectWriter"}]},
)
s3_resource.meta.client.delete_public_access_block(Bucket=first_bucket_name)

second_file_name = create_temp_file(400, "secondfile.txt", "s")
second_object = s3_resource.Object(first_bucket.name, second_file_name)
second_object.upload_file(second_file_name, ExtraArgs={"ACL": "public-read"})
second_object_acl = second_object.Acl()
print(second_object_acl.grants)
response = second_object_acl.put(ACL="private")
print(second_object_acl.grants)

# Encryption
third_file_name = create_temp_file(300, "thirdfile.txt", "t")
third_object = s3_resource.Object(first_bucket_name, third_file_name)
third_object.upload_file(
third_file_name, ExtraArgs={"ServerSideEncryption": "AES256"}
)
print(third_object.server_side_encryption)

# Storage
third_object.upload_file(
third_file_name,
ExtraArgs={
"ServerSideEncryption": "AES256",
"StorageClass": "STANDARD_IA",
},
)
third_object.reload()
print(third_object.storage_class)

# Versioning
enable_bucket_versioning(first_bucket_name)
s3_resource.Object(first_bucket_name, first_file_name).upload_file(
first_file_name
)
s3_resource.Object(first_bucket_name, first_file_name).upload_file(
third_file_name
)
s3_resource.Object(first_bucket_name, second_file_name).upload_file(
second_file_name
)
print(s3_resource.Object(first_bucket_name, first_file_name).version_id)

# Traversals: Bucket Traversal
for bucket in s3_resource.buckets.all():
print(bucket.name)

for bucket_dict in s3_resource.meta.client.list_buckets().get("Buckets"):
print(bucket_dict["Name"])

# Object Traversal
for obj in first_bucket.objects.all():
print(obj.key)

for obj in first_bucket.objects.all():
subsrc = obj.Object()
print(
obj.key,
obj.storage_class,
obj.last_modified,
subsrc.version_id,
subsrc.metadata,
)

# Deleting Buckets and Objects
delete_all_objects(first_bucket_name)
s3_resource.Object(second_bucket_name, first_file_name).upload_file(
first_file_name
)
delete_all_objects(second_bucket_name)

s3_resource.Bucket(first_bucket_name).delete()
s3_resource.meta.client.delete_bucket(Bucket=second_bucket_name)
Loading