DEV Community

Ayman Aly Mahmoud
Ayman Aly Mahmoud

Posted on

Python Lambda function example:

Python Lambda function example:

import boto3
from PIL import Image
import io

s3 = boto3.client('s3')

def lambda_handler(event, context):
    # Get bucket and object key from the event
    bucket = event['Records'][0]['s3']['bucket']['name']
    key = event['Records'][0]['s3']['object']['key']

    # Download the image from S3
    response = s3.get_object(Bucket=bucket, Key=key)
    image = Image.open(io.BytesIO(response['Body'].read()))

    # Create a thumbnail
    image.thumbnail((100, 100))

    # Save the thumbnail to a new S3 key
    thumbnail_key = f"thumbnails/{key}"
    buffer = io.BytesIO()
    image.save(buffer, 'JPEG')
    buffer.seek(0)
    s3.put_object(Bucket=bucket, Key=thumbnail_key, Body=buffer, ContentType='image/jpeg')

    return {'statusCode': 200, 'body': f'Thumbnail saved to {thumbnail_key}'}
Enter fullscreen mode Exit fullscreen mode

Explanation of Important Parts:

  1. Imports (boto3 and PIL):
    • boto3 is the AWS SDK for Python, allowing interaction with AWS services (S3 in this case).
    • PIL (Pillow) is a library for image processing, used here to create a thumbnail.
  2. AWS S3 Client (s3 = boto3.client('s3')):

    Creates an S3 client to interact with Amazon S3.

  3. Handler Function (lambda_handler):

    The main entry point for the Lambda function, triggered by an S3 event when an image is uploaded to a bucket.

  4. Extracting S3 Information (bucket and key):

    The event contains information about the S3 bucket and the object (image) that triggered the Lambda function.

  5. Download the Image (s3.get_object):

    Downloads the image from the S3 bucket using the get_object method.

  6. Image Processing (image.thumbnail):

    Uses the Pillow library to create a thumbnail of the image with a maximum size of 100x100 pixels.

  7. Upload the Thumbnail (s3.put_object):

    Saves the thumbnail back to the S3 bucket under a new key (thumbnails/{key}).

  8. Return Statement:

    Returns a simple JSON response indicating where the thumbnail was saved.

Lambda layers

Lambda layers

Without layers:

Two Lambda functions (function 1 and function 2) each with their own function code and dependencies. Function 1 also includes a custom run time.

With layers:

  • Lambda function 1 and Lambda function 2 include only function code.
  • Lambda function 1 uses Lambda layer 1 for its custom runtime and Lambda layer 2 for its code dependencies.
  • Lambda function 2 uses Lambda layer 2 for its code dependencies.

A Lambda layer is a .zip file archive that contains supplementary code or data. Layers usually contain library dependencies, a custom runtime, or configuration files. You can also package your own custom runtime in a Lambda layer if you prefer a different runtime from those provided by the Lambda service.

There are multiple reasons why you might consider using layers:

  1. Reduce the size of your deployment packages: Instead of including all of your function dependencies along with your function code in your deployment package, put them in a layer. This keeps deployment packages small and organized.
  2. Separate core function logic from dependencies: With layers, you can update your function dependencies independent of your function code, and vice versa. This promotes separation of concerns and helps you focus on your function logic.
  3. Share dependencies across multiple functions: After you create a layer, you can apply it to any number of functions in your account. Without layers, you need to include the same dependencies in each individual deployment package.
  4. Use the Lambda console code editor: The code editor is a useful tool for testing minor function code updates quickly. However, you can’t use the editor if your deployment package size is too large. Using layers reduces your package size and can unlock usage of the code editor.

Summary of what we learned in this series

  • AWS Lambda is a service to run code functions without provisioning or managing servers.
  • A Lambda function can run inside a VPC owned by the AWS Lambda service or as Lambda@Edge in an Amazon CloudFront regional cache.
  • A Lambda function can be configured to connect to your VPC to access AWS services inside the VPC.
  • A Lambda function can be invoked synchronously, asynchronously, and with event source mappings for queues and streams.
  • Use Lambda layers to package code dependencies or custom runtimes to be re-used by all Lambda functions in the Region.

Top comments (0)