التخطي إلى المحتوى الرئيسي

DynamoDb CRUD Operation Code using Lambda

Utilizing DynamoDB with AWS Lambda and Boto3

Presentation

DynamoDB is a completely overseen NoSQL information base help given by AWS that supports key-worth and report information structures. AWS Lambda is a serverless process administration that runs your code because of occasions and consequently deals with the fundamental register assets. Boto3 is the Amazon Web Administrations (AWS) SDK for Python, which permits Python designers to compose programming that utilizes administrations like Amazon S3, Amazon EC2, and DynamoDB.


Setting Up

1. Make a DynamoDB Table

To begin with, make a DynamoDB table to store your information. You can do this utilizing the AWS The executives Control center or automatically utilizing Boto3.


Model: Making a Table Utilizing Boto3


python

import boto3


# Make a DynamoDB client

dynamodb = boto3.client('dynamodb')


# Make a table

dynamodb.create_table(

    TableName='Students',

    KeySchema=[

        {

            'AttributeName': 'RollNumber',

            'KeyType': 'HASH' # Segment key

        }

    ],

    AttributeDefinitions=[

        {

            'AttributeName': 'RollNumber',

            'AttributeType': 'N'

        }

    ],

    BillingMode='PAY_PER_REQUEST'

)

2. Make an AWS Lambda Capability

Then, make an AWS Lambda capability that will connect with your DynamoDB table.


Model: Making a Lambda Capability Utilizing Boto3


python

import boto3


# Make a DynamoDB asset

dynamodb = boto3.resource('dynamodb')


def lambda_handler(event, setting):

    # Your code here

    pass

Embedding Records

1. Embed a Record Utilizing PutItem

To embed a record into your DynamoDB table, utilize the PutItem Programming interface.


Model: Embedding a Record


python

def lambda_handler(event, setting):

    table = dynamodb.Table('Students')


    reaction = table.put_item(

        Item={

            'RollNumber': 1,

            'Name': 'John Doe'

        }

    )


    bring reaction back

Refreshing Records

1. Update a Record Utilizing UpdateItem

To refresh a record in your DynamoDB table, utilize the UpdateItem Programming interface.


Model: Refreshing a Record


python

def lambda_handler(event, setting):

    table = dynamodb.Table('Students')


    reaction = table.update_item(

        Key={'RollNumber': 1},

        UpdateExpression='SET Name = :val1',

        ExpressionAttributeValues={

            ':val1': 'Jane Doe'

        }

    )


    bring reaction back

Erasing Records

1. Erase a Record Utilizing DeleteItem

To erase a record from your DynamoDB table, utilize the DeleteItem Programming interface.


Model: Erasing a Record


python

def lambda_handler(event, setting):

    table = dynamodb.Table('Students')


    reaction = table.delete_item(

        Key={'RollNumber': 1}

    )


    return



 1)  Create Table under dynamodb Tablename Employee (EmpId,Empname,Age)


2) Create Lambda Function to Insert and Show Record

import json

import boto3

from botocore.exceptions import ClientError

import showdata

# Create a DynamoDB client

dynamodb = boto3.resource('dynamodb')

table = dynamodb.Table('Employee')  # Replace with your table name


def lambda_handler(event, context):

    # Data to insert (you can modify this based on the incoming event or hardcode)

    item = {

        'EmpID':'113',  # Partition key, replace as needed

        'Empname': 'Ravi',

        'Age': 30

    }


    try:

        # Insert the item into the DynamoDB table

        table.put_item(Item=item)

        print('Item inserted successfully!')

        showdata.fun()

       

        

    except ClientError as e:

        print(f"Error inserting item: {e}")

        return {

            'statusCode': 500,

            'body': json.dumps('Failed to insert item')

        }



for show:

import boto3
import json
import os
from decimal import Decimal
def decimal_to_float(obj):
    if isinstance(obj, list):
        return [decimal_to_float(i) for i in obj]
    elif isinstance(obj, dict):
        return {k: decimal_to_float(v) for k, v in obj.items()}
    elif isinstance(obj, Decimal):
        return float(obj)
    return obj

def fun():
    # Initialize DynamoDB resource
    dynamodb = boto3.resource('dynamodb')
    
    # Table name (replace with your table name)
    table_name = os.environ.get('DYNAMODB_TABLE', 'Employee')
    
    # Access the table
    table = dynamodb.Table(table_name)
    
    try:
        # Example: Query based on a primary key (adjust the KeyConditionExpression as per your schema)
        response = table.query(
            KeyConditionExpression=boto3.dynamodb.conditions.Key('EmpID').eq('111')
        )
        
        # Retrieve items from the response
        items =decimal_to_float(response.get('Items', []))
        print(items)
        return {
            'statusCode': 200,
            'body': json.dumps(items)
        }
    except Exception as e:
        print(f"Error fetching data from DynamoDB: {str(e)}")
        return {
            'statusCode': 500,
            'body': json.dumps({'error': 'Failed to fetch data'})
        }




3)  Manage Policy 

{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:Query",
"dynamodb:GetItem"
],
"Resource": "arn:aws:dynamodb:ap-south-1:<accountid>:table/Employee"
}
]
}
Code to Select and Insert Record

import json
import boto3
from botocore.exceptions import ClientError
import crudstudents
def lambda_handler(event, context):
     dynamodb = boto3.resource('dynamodb')
     crudstudents.showstudent()
     return {
        'statusCode': 200,
        'body': json.dumps('Hello from Lambda!')}


code of crudstudents.py

import boto3
def insertStudent():
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Student')
    item = {

        'rno':'1003',  # Partition key, replace as needed

        'name': 'test',

        'branch': 'CS',
        
         'fees':45000

    }
    table.put_item(Item=item)
    print('Item inserted successfully!')

def showstudent():
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Student')
    response = table.scan() 
    data = response['Items']
    print(data)


Role:
Assign an IAM Role:     Create a new role with AmazonDynamoDBReadOnlyAccess and AWSLambdaBasicExecutionRole permissions, or use an existing role with these permissions.


Dynamodb Another Example:

For Insert, Update and Select Record
import json
import boto3


def lambda_handler(event, context):
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('Student')
    #reaction = table.put_item(Item={'Enrollno': 'SCS1007','Name': 'Allon Musk'})
    table.update_item(
        Key={'Enrollno': 'SCS1001','Name':'Trayambak Pandey'},
        UpdateExpression='SET #n = :v',
        ExpressionAttributeNames={'#n': 'Qualification'},
        ExpressionAttributeValues={':v': 'PHD'}
    )
    response = table.scan()
    items = response['Items']

    # TODO implement
    return {
        'statusCode': 200,
        'body': json.dumps(items)
    }


Code for Permission
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "Statement1",
"Effect": "Allow",
"Action": [
"dynamodb:PutItem",
"dynamodb:UpdateItem",
"dynamodb:Query",
"dynamodb:Scan",
"dynamodb:GetItem"
],
"Resource": "arn:aws:dynamodb:ap-south-1:288542289586:table/Student"
}
]
}



تعليقات

المشاركات الشائعة من هذه المدونة

Uncontrolled form input in React-JS

  Uncontrolled form input in React-JS? If we want to take input from users without any separate event handling then we can uncontrolled the data binding technique. The uncontrolled input is similar to the traditional HTML form inputs. The DOM itself handles the form data. Here, the HTML elements maintain their own state that will be updated when the input value changes. To write an uncontrolled component, you need to use a ref to get form values from the DOM. In other words, there is no need to write an event handler for every state update. You can use a ref to access the input field value of the form from the DOM. Example of Uncontrolled Form Input:- import React from "react" ; export class Info extends React . Component {     constructor ( props )     {         super ( props );         this . fun = this . fun . bind ( this ); //event method binding         this . input = React . createRef ();...

JSP Page design using Internal CSS

  JSP is used to design the user interface of an application, CSS is used to provide set of properties. Jsp provide proper page template to create user interface of dynamic web application. We can write CSS using three different ways 1)  inline CSS:-   we will write CSS tag under HTML elements <div style="width:200px; height:100px; background-color:green;"></div> 2)  Internal CSS:-  we will write CSS under <style> block. <style type="text/css"> #abc { width:200px;  height:100px;  background-color:green; } </style> <div id="abc"></div> 3) External CSS:-  we will write CSS to create a separate file and link it into HTML Web pages. create a separate file and named it style.css #abc { width:200px;  height:100px;  background-color:green; } go into Jsp page and link style.css <link href="style.css"  type="text/css" rel="stylesheet"   /> <div id="abc"> </div> Exam...

JDBC using JSP and Servlet

JDBC means Java Database Connectivity ,It is intermediates from Application to database. JDBC has different type of divers and provides to communicate from database server. JDBC contain four different type of approach to communicate with Database Type 1:- JDBC-ODBC Driver Type2:- JDBC Vendor specific Type3 :- JDBC Network Specific Type4:- JDBC Client-Server based Driver  or JAVA thin driver:- Mostly we prefer Type 4 type of Driver to communicate with database server. Step for JDBC:- 1  Create Database using MYSQL ,ORACLE ,MS-SQL or any other database 2   Create Table using database server 3   Create Form according to database table 4  Submit Form and get form data into servlet 5  write JDBC Code:-     5.1)   import package    import java.sql.*     5.2)  Add JDBC Driver according to database ide tools     5.3)  call driver in program         ...