0

I'm trying to create an item in DynamoDB table using Lambda function using random number generation. I can't use Put-Item function and it has to be generated using random_number generation. `

import json
import boto3
import os
import logging
import random

def generate_random_number():
    return random.randint(1, 1000000)

thingName = 'abc'

logger = logging.getLogger()
logger.setLevel(logging.INFO)

iot_client = boto3.client('iot', region_name=os.environ['AWS_REGION'])

endpoint_response = iot_client.describe_endpoint(endpointType='iot:Data-ATS')
endpoint_url = f"https://{endpoint_response['endpointAddress']}"

iot_shadow_client = boto3.client('iot-data', region_name=os.environ['AWS_REGION'], endpoint_url=endpoint_url)

def lambda_handler(event, context):
    payload_data = json.loads(event['body'])
    data = payload_data.get('inputs')
    payload_str = json.dumps(data)
    payload_bytes = payload_str.encode('utf-8')
    logger.info(payload_bytes)
    update_response = iot_shadow_client.update_thing_shadow(
        thingName=thingName,
        payload=payload_bytes
    )
    output = update_response.get('payload').read().decode("utf-8")
    print(output)
    logger.info(output)
    dynamodb = boto3.resource('dynamodb')
    tables = dynamodb.tables.all()
    for tbl in tables:
        table = dynamodb.Table(xxxx)

    id = generate_random_number()
    print("id", id)

    return {
        'statusCode': 200,
        'headers': {
            'Access-Control-Allow-Headers': 'Content-Type',
            'Access-Control-Allow-Origin': '*',
            'Access-Control-Allow-Methods': 'OPTIONS,POST'
        },
        'body': output
    }
`

It keeps failing at generating payload payload_data = json.loads(event['body'])

1
  • "It keeps failing" Failing how? Is there an error message or exception or something? If so, please edit your question to include those relevant details.
    – Mark B
    Commented Feb 12, 2024 at 15:15

1 Answer 1

0

This part of your code makes no sense:

dynamodb = boto3.resource('dynamodb')
    tables = dynamodb.tables.all()
    for tbl in tables:
        table = dynamodb.Table(xxxx)

    id = generate_random_number()
    print("id", id)

Essentially you call ListTables then assign a table to the resource in a loop. But you don't actually try to add any data.

Then you print an id.

You can't expect to put data in DynamoDB without using a PutItem or UpdateItem etc...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.