Debug School

rakesh kumar
rakesh kumar

Posted on

How to Integrate AWS Lambda function in django to image processing

S3 Image Processing (using Pillow):

from PIL import Image
import boto3
import os

def lambda_handler(event, context):
    s3 = boto3.client('s3')
    bucket_name = event['bucket_name']
    file_key = event['file_key']

    # Download image from S3
    local_path = '/tmp/' + file_key
    s3.download_file(bucket_name, file_key, local_path)

    # Process image (resize)
    image = Image.open(local_path)
    resized_image = image.resize((100, 100))

    # Save processed image back to S3
    processed_key = 'processed/' + file_key
    local_path_processed = '/tmp/' + processed_key
    resized_image.save(local_path_processed)
    s3.upload_file(local_path_processed, bucket_name, processed_key)

    return f"Image {file_key} processed and saved as {processed_key}."
Enter fullscreen mode Exit fullscreen mode

Input:
{
"bucket_name": "your-s3-bucket",
"file_key": "example.jpg"
}
Output:
save this file as resize_file.py

Image description

refrence

Image description
If you've deployed the Lambda function with the AWS CLI, you can find the function name or ARN in the AWS Lambda Console or by using the AWS CLI:

aws lambda list-functions
Enter fullscreen mode Exit fullscreen mode

"Image example.jpg processed and saved as processed/example.jpg."
6-10: DynamoDB Operations

To integrate the provided AWS Lambda function for image processing (resizing) with a Django project, you can create a Django view that triggers the Lambda function. The Django view can receive the S3 object-related information (bucket name and file key) from a client and invoke the Lambda function using the Boto3 library. Below are the steps and an example implementation:

Configure Boto3 in Your Django Project:

Install the boto3 library if you haven't already:

pip install boto3
Enter fullscreen mode Exit fullscreen mode

Configure AWS credentials in your Django project (either through environment variables, AWS CLI, or IAM roles). Ensure that the IAM role associated with your Lambda function has the necessary permissions to read from and write to S3.

Create a Django Template (image_process_form.html):

<!-- templates/image_process_form.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Resize and Download Image with Lambda</title>
</head>
<body>
    <h2>Resize and Download Image with Lambda</h2>
    <form method="post" action="{% url 'resize-and-download-image' %}">
        {% csrf_token %}
        <label for="bucket_name">Bucket Name:</label>
        <input type="text" name="bucket_name" required><br>

        <label for="file_key">File Key:</label>
        <input type="text" name="file_key" required><br>

        <button type="submit">Resize and Download Image</button>
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Create a Django View (views.py):

# views.py
from django.http import JsonResponse
from django.shortcuts import render
import boto3
import json

def resize_and_download_image(request):
    if request.method == 'POST':
        try:
            # Extract S3 object-related information from the form data
            bucket_name = request.POST.get('bucket_name')
            file_key = request.POST.get('file_key')

            # Create a Boto3 Lambda client
            lambda_client = boto3.client('lambda', region_name='your-aws-region')

            # Invoke the Lambda function to resize and download the image
            lambda_client.invoke(
                FunctionName='resize_file',
                InvocationType='Event',  # Asynchronous invocation
                Payload=json.dumps({
                    'bucket_name': bucket_name,
                    'file_key': file_key
                })
            )

            # Return a JsonResponse indicating the successful initiation of the image resizing and download
            return JsonResponse({'message': f"Image {file_key} resizing and download request sent to Lambda."}, status=200)

        except Exception as e:
            # Return a JsonResponse indicating an error if any occurs
            return JsonResponse({'error': str(e)}, status=500)

    else:
        # Render the form for GET requests
        return render(request, 'image_process_form.html')
Enter fullscreen mode Exit fullscreen mode

Define URLs in Django (urls.py):

# urls.py
from django.urls import path
from .views import resize_and_download_image

urlpatterns = [
    path('resize-and-download/', resize_and_download_image, name='resize-and-download-image'),
    # Add other URL patterns as needed
]
Enter fullscreen mode Exit fullscreen mode

Run Django Development Server:

Start your Django project's development server.

python manage.py runserver
Enter fullscreen mode Exit fullscreen mode

Now, if you navigate to http://localhost:8000/resize-and-download/ in your browser, you should see the form for resizing and downloading an image with Lambda. Users can fill in the bucket name and file key, and when they submit the form, the image resizing and download request will be sent to the Lambda function.

Remember to replace 'your-aws-region' and 'your-lambda-function-name' with your actual AWS region and Lambda function name. Adjust the code based on your specific needs and requirements.

Top comments (0)