Python AWS S3

S3 buckets and objects, presigned URLs and S3-compatible stores from Python services.

Zato lets you work with Amazon S3 directly from your Python services. You create an AWS connection in the Dashboard, and the S3 client is available under conn.s3 - the same client that boto3.client('s3') returns, with credentials and configuration managed for you.

Storing and reading objects

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class CreateInvoiceBackup(Service):

    input = 'invoice_id', 'data'

    def handle(self):

        # Get the connection by its Dashboard name
        conn = self.aws['My AWS']

        # Store an object in S3
        conn.s3.put_object(
            Bucket='invoices',
            Key=self.request.input.invoice_id,
            Body=self.request.input.data,
        )

        # Read it back
        response = conn.s3.get_object(Bucket='invoices', Key=self.request.input.invoice_id)
        self.response.payload = response['Body'].read()

Listing buckets and objects

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class ListInvoices(Service):

    def handle(self):

        conn = self.aws['My AWS']

        # All the buckets the credentials can see
        buckets = conn.s3.list_buckets()

        # All the objects under a prefix in one bucket
        response = conn.s3.list_objects_v2(Bucket='invoices', Prefix='2026/')

        names = []
        for item in response['Contents']:
            names.append(item['Key'])

        self.response.payload = {'names': names}

Deleting objects

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class DeleteInvoice(Service):

    input = 'invoice_id'

    def handle(self):

        conn = self.aws['My AWS']

        conn.s3.delete_object(Bucket='invoices', Key=self.request.input.invoice_id)

Presigned URLs

Presigned URLs let external clients download or upload a specific object for a limited time, without having AWS credentials of their own.

# -*- coding: utf-8 -*-

# Zato
from zato.server.service import Service

class GetInvoiceDownloadLink(Service):

    input = 'invoice_id'

    def handle(self):

        conn = self.aws['My AWS']

        # A download link that expires after one hour
        url = conn.s3.generate_presigned_url(
            'get_object',
            Params={'Bucket': 'invoices', 'Key': self.request.input.invoice_id},
            ExpiresIn=3600,
        )

        self.response.payload = {'url': url}

S3-compatible stores

The connection's optional "Endpoint URL" field lets you point the same code at any S3-compatible object store instead of AWS - fill it in with the store's address and everything else stays the same.

More resources

Learn more