Debug School

rakesh kumar
rakesh kumar

Posted on

How to integrate AWS Lambda function in django to perform arithmatic operation

To integrate the provided AWS Lambda function code with your Django project, you can create a Django view that communicates with the AWS Lambda function. This involves sending the required input to the Lambda function and receiving the result. 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.

Define a View in Django:

Create a Django view that sends the input to the AWS Lambda function and processes the result.

import boto3
from django.http import JsonResponse

def perform_arithmetic_operation(request, num1, num2, operator):
    # Adjust this to your AWS Lambda function name and region
    lambda_function_name = 'your-lambda-function-name'
    aws_region = 'your-aws-region'

    # Create a Boto3 Lambda client
    lambda_client = boto3.client('lambda', region_name=aws_region)

    # Prepare the payload for the Lambda function
    payload = {
        'num1': float(num1),
        'num2': float(num2),
        'operator': operator

        # Invoke the Lambda function
        response = lambda_client.invoke(

        # Read and parse the Lambda function response
        result = json.loads(response['Payload'].read().decode('utf-8'))

        return JsonResponse({'result': result}, status=200)
    except Exception as e:
        return JsonResponse({'error': str(e)}, status=500)
Enter fullscreen mode Exit fullscreen mode

Define URLs in Django:

Include the URL pattern for the new view. Modify this according to your project's URL structure.

from django.urls import path
from .views import perform_arithmetic_operation

urlpatterns = [
    path('arithmetic/<num1>/<num2>/<operator>/', perform_arithmetic_operation, name='arithmetic-operation'),
    # Add other URL patterns as needed
Enter fullscreen mode Exit fullscreen mode

Run Django Development Server:

Start your Django project's development server.

python runserver
Enter fullscreen mode Exit fullscreen mode

Now, when you navigate to a URL like http://localhost:8000/arithmetic/5/3/add/, the view will send the input values to your AWS Lambda function, and the result will be displayed in the browser.

Adjust the lambda_function_name and aws_region variables to match your Lambda function's name and the AWS region where it's deployed. This example assumes that the Lambda function takes input in the format provided by the URL parameters (num1, num2, operator), and it returns a JSON response with the result. Adapt this code based on your specific Lambda function input requirements.

Top comments (0)