Debug School

rakesh kumar
rakesh kumar

Posted on

How to Integrate AWS Lambda function in django to upload and deletes an object from an S3 bucket

The provided code, the upload_file_to_s3 view expects a POST request with specific parameters (bucket_name, file_key, and file_content). This can be achieved using a form in a Django template. Below is an example of how you might create a Django template file and the associated form for uploading a file to S3:
In Aws console

import boto3

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

    s3.put_object(Bucket=bucket_name, Key=file_key, Body=file_content)
    return f"File {file_key} uploaded successfully."
Enter fullscreen mode Exit fullscreen mode

save this file as upload_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

Input:

{
    "bucket_name": "your-s3-bucket"
}
Enter fullscreen mode Exit fullscreen mode

Output:

{
    "Contents": [
        {"Key": "file1.txt", "Size": 1024},
        {"Key": "file2.jpg", "Size": 2048}
    ]
}
Enter fullscreen mode Exit fullscreen mode

Integrate with Django Project
Create a Django Template (upload_form.html):


<!-- templates/upload_form.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Upload File to S3</title>
</head>
<body>
    <h2>Upload File to S3</h2>
    <form method="post" action="{% url 'upload-file-to-s3' %}" enctype="multipart/form-data">
        {% 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>

        <label for="file_content">File Content:</label>
        <input type="file" name="file_content" required><br>

        <button type="submit">Upload File</button>
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Modify the Django View (views.py):

import boto3
import json
from django.http import JsonResponse, HttpResponse
from django.shortcuts import render

def upload_file_to_s3(request):
    if request.method == 'POST':
        try:
            # Extract file-related information from the form data
            bucket_name = request.POST.get('bucket_name')
            file_key = request.POST.get('file_key')
            file_content = request.FILES['file_content'].read()

            # Create a Boto3 S3 client
            s3_client = boto3.client('s3')

            # Invoke the Lambda function to upload the file
            lambda_client = boto3.client('lambda', region_name='your-aws-region')
            lambda_client.invoke(
                FunctionName='upload_file',
                InvocationType='Event',  # Asynchronous invocation
                Payload=json.dumps({
                    'bucket_name': bucket_name,
                    'file_key': file_key,
                    'file_content': file_content.decode('utf-8')
                })
            )

            return JsonResponse({'message': f"File {file_key} upload request sent to Lambda."}, status=200)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    else:
        # Render the form for GET requests
        return render(request, 'upload_form.html')
Enter fullscreen mode Exit fullscreen mode

Define URLs in Django (urls.py):

from django.urls import path
from .views import upload_file_to_s3

urlpatterns = [
    path('upload/', upload_file_to_s3, name='upload-file-to-s3'),
    # 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/upload/ in your browser, you should see the form for uploading a file to S3. Users can fill in the bucket name, file key, and choose a file to upload. When they submit the form, the file upload request will be sent to the Lambda function.

Make sure to replace 'your-aws-region' and 'your-lambda-function-name' with your actual AWS region and Lambda function name in the Django view. Adjust the form and view as needed based on your specific requirements.

Deletes the object from S3 in

import boto3

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

    s3.delete_object(Bucket=bucket_name, Key=file_key)
    return f"File {file_key} deleted successfully."
Enter fullscreen mode Exit fullscreen mode

save this file as delete_file.py
Input:


{
    "bucket_name": "your-s3-bucket",
    "file_key": "example.txt"
}
Enter fullscreen mode Exit fullscreen mode

Output:

"File example.txt deleted successfully.
Enter fullscreen mode Exit fullscreen mode

"
Integrate with Django Project
To integrate your AWS Lambda function, which deletes an object from an S3 bucket, 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 delete objects from S3.

Create a Django Template (delete_form.html):

<!-- templates/delete_form.html -->
<!DOCTYPE html>
<html>
<head>
    <title>Delete File from S3</title>
</head>
<body>
    <h2>Delete File from S3</h2>
    <form method="post" action="{% url 'delete-file-from-s3' %}">
        {% 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">Delete File</button>
    </form>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Create a Django View (views.py):

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

def delete_file_from_s3(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 S3 client
            s3_client = boto3.client('s3')

            # Invoke the Lambda function to delete the file
            lambda_client = boto3.client('lambda', region_name='your-aws-region')
            lambda_client.invoke(
                FunctionName='delete_file',
                InvocationType='Event',  # Asynchronous invocation
                Payload=json.dumps({
                    'bucket_name': bucket_name,
                    'file_key': file_key
                })
            )

            return JsonResponse({'message': f"File {file_key} deletion request sent to Lambda."}, status=200)

        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    else:
        # Render the form for GET requests
        return render(request, 'delete_form.html')
Enter fullscreen mode Exit fullscreen mode

Define URLs in Django (urls.py):

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

urlpatterns = [
    path('delete/', delete_file_from_s3, name='delete-file-from-s3'),
    # 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/delete/ in your browser, you should see the form for deleting a file from S3. Users can fill in the bucket name and file key, and when they submit the form, the file deletion request will be sent to the Lambda function.

Make sure to replace 'your-aws-region' and 'your-lambda-function-name' with your actual AWS region and Lambda function name in the Django view. Adjust the form and view as needed based on your specific requirements.

Top comments (0)