dlaser
dlaser

Reputation: 1345

Can't add item to dynamodb table with python

I was trying to add an item to a dynamodb table, using the boto library. It seemed straightforward. The code I have is:

import boto.dynamodb

c = boto.dynamodb.connect_to_region(aws_access_key_id="xxx",
                                    aws_secret_access_key="xxx",
                                    region_name="us-west-2")

users = c.get_table("users")

users.put_item(data={'username': 'johndoe', 
                     'first_name': 'John',
                     'last_name': 'Doe'})

However, I get the following error:

'Table' object has no attribute 'put_item'

I think I connected to the database fine, and got the users table fine (the users variable is of the type: boto.dynamodb.table.Table). So, I am not sure why it can't find the put_item method (I even checked the code for the Table class in the boto library, and it has the put_item method). Any insights would be highly appreciated.

Upvotes: 3

Views: 7717

Answers (1)

kukido
kukido

Reputation: 10601

You are using DynamoDB v1 interface. For that use the following syntax:

item_data = {
    'Body': 'http://url_to_lolcat.gif',
    'SentBy': 'User A',
    'ReceivedTime': '12/9/2011 11:36:03 PM',
}

item = table.new_item(
    # Our hash key is 'forum'
    hash_key='LOLCat Forum',
    # Our range key is 'subject'
    range_key='Check this out!',
    # This has the
    attrs=item_data
)

Source: An Introduction to boto’s DynamoDB interface

I suggest to migrate to DynamoDB v2 interface: An Introduction to boto’s DynamoDB v2 interface

from boto.dynamodb2.table import Table

table = Table('users')

users.put_item(data={'username': 'johndoe', 
                     'first_name': 'John',
                     'last_name': 'Doe'})

Upvotes: 5

Related Questions