pynamodb / PynamoDB

A pythonic interface to Amazon's DynamoDB
http://pynamodb.readthedocs.io
MIT License
2.44k stars 427 forks source link

Example of AWS Lambda usage #1224

Closed supreme-core closed 5 months ago

supreme-core commented 8 months ago

Hi,

Where can I find examples of using PynamoDB inside an AWS lambda function?

Much appreciated!

supreme-core commented 8 months ago

I sorta got it going with python-lambda (https://github.com/nficano/python-lambda/tree/master)

pip install python-lambda
mkdir myfunc1 && cd myfunc1
lambda init

Commands above initialized a working environment of a lambda function.

  1. Open config.yaml to fill in the aws_access_key_id and aws_secret_access_key
  2. Open service.py and replace the content with the code below
from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute

class UserModel(Model):
        """
        A DynamoDB User
        """
        class Meta:
            table_name = "dynamodb-user"
        email = UnicodeAttribute(null=True)
        first_name = UnicodeAttribute(range_key=True)
        last_name = UnicodeAttribute(hash_key=True)

def handler(event, context):
    # Your code goes here!
    # e = event.get("e")
    # pi = event.get("pi")
    # return e + pi

    if not UserModel.exists():
        # Create the table
        UserModel.create_table(read_capacity_units=1, write_capacity_units=1, wait=True)
    user = UserModel("John", "Denver")
    user.email = "djohn@company.org"
    user.save()

Then, test it locally

lambda invoke -v

This is good, however it can't deploy to AWS when I ran deployment

lambda deploy

It threw botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the GetFunction operation: The security token included in the request is invalid.

I think it has to do with the way boto communicates with AWS underneath.

supreme-core commented 5 months ago

Didn't receive a reply. Closing it.