Iām far from a Python expert, but working on a quick interaction script with Object Storage was a fun way to stretch my skills with the language while testing our new storage product.
This example uses boto3
and it works off the shelf with no significant changes. Give it a try! Also, Python critiques are welcome
import boto3
from botocore.exceptions import BotoCoreError, ClientError
# Configuration for Fastly Object store
ACCESS_KEY = "{KEY}" # Replace with your Object Storage access key
SECRET_KEY = "{SECRET}" # Replace with your Object Storage secret key
ENDPOINT_URL = "https://us-west.object.fastlystorage.app" # Replace with your Fastly endpoint
BUCKET_NAME = "my-bucket"
REGION = "us-west" # Replace with your Object Storage region
# Create an S3 client
object_store_client = boto3.client(
"s3",
aws_access_key_id=ACCESS_KEY,
aws_secret_access_key=SECRET_KEY,
endpoint_url=ENDPOINT_URL,
region_name = REGION,
)
# Function to list objects in the bucket
def list_objects():
print(f"Listing objects in bucket '{BUCKET_NAME}'...")
try:
response = object_store_client.list_objects_v2(Bucket=BUCKET_NAME)
if "Contents" in response:
print("Objects in the bucket:")
for obj in response["Contents"]:
print(f" - {obj['Key']}")
else:
print("The bucket is empty.")
except (BotoCoreError, ClientError) as e:
print(f"Error listing objects: {e}")
# Function to write an object to the bucket
def write_object():
object_key = input("Enter the object key (filename): ")
content = input("Enter the content to write: ")
print(f"Writing object '{object_key}' to bucket '{BUCKET_NAME}'...")
try:
object_store_client.put_object(Bucket=BUCKET_NAME, Key=object_key, Body=content)
print(f"Object '{object_key}' successfully written to the bucket.")
except (BotoCoreError, ClientError) as e:
print(f"Error writing object: {e}")
# Main program
if __name__ == "__main__":
print("Hello, World! Connecting to Fastly Object Store...")
print("Choose an operation:")
print("1. List objects")
print("2. Write an object")
operation = input("Enter your choice: ")
if operation == "1":
list_objects()
elif operation == "2":
write_object()
else:
print("Invalid operation selected.")