使用boto将项数据添加到DynamoDB表不起作用

时间:2015-09-28 16:13:20

标签: python add amazon-dynamodb boto items

我一直在尝试使用boto将项添加到DynamoDB表中,但不知何故它似乎不起作用。我尝试使用users.Item()和users.put_item但没有任何效果。下面是我使用的脚本。     import boto.dynamodb2     import boto.dynamodb2.items     导入json     来自boto.dynamodb2.fields导入HashKey,RangeKey,GlobalAllIndex     来自boto.dynamodb2.layer1导入DynamoDBConnection     来自boto.dynamodb2.table导入表     来自boto.dynamodb2.items导入项目     来自boto.dynamodb2.types导入NUMBER

In [25]: df
Out[25]:
   Record_ID                       Time
0      94704 2014-03-10 07:19:19.647342
1      94705 2014-03-10 07:21:44.479363
2      94706 2014-03-10 07:21:45.479581
3      94707 2014-03-10 07:21:54.481588
4      94708 2014-03-10 07:21:55.481804

In [26]: type(df['Time'][0])
Out[26]: pandas.tslib.Timestamp

In [27]: df['Time'] = df['Time'].apply(lambda x: x.replace(microsecond=0))

In [28]: df
Out[28]:
   Record_ID                Time
0      94704 2014-03-10 07:19:19
1      94705 2014-03-10 07:21:44
2      94706 2014-03-10 07:21:45
3      94707 2014-03-10 07:21:54
4      94708 2014-03-10 07:21:55

我试过这个,表格被创建了,很好。但是当我尝试输入项目时,我收到以下错误消息。

region = "us-east-1"
con = boto.dynamodb2.connect_to_region(region)
gettables = con.list_tables()
mytable = "my_table"

if mytable not in gettables['TableNames']:
    print "The table *%s* is not in the list of tables created. A new table will be created." % req_table
    Table.create(req_table,
              schema = [HashKey('username'),
                        RangeKey('ID', data_type = NUMBER)],
             throughput = {'read': 1, 'write': 1})
else:    
    print "The table *%s* exists." % req_table

con2table = Table(req_table,connection=con)
con2table.put_item(data={'username': 'abcd',
                         'ID': '001',
                         'logins':'10',
                         'timeouts':'20'
                         'daysabsent': '30'
                         })

谢谢。

2 个答案:

答案 0 :(得分:0)

从您收到的错误消息中,听起来您正在尝试为在DynamoDB中定义为数字的属性发送字符串值。

具体问题与您的范围键ID相关,后者定义为数字值N,但您发送的字符串值为'001'

答案 1 :(得分:0)

看起来您尝试加载的值具有空值。 当我试图加载它时,我得到了同样的错误。当partner_name属性为空字符串时,我遇到异常。

try:
  item_old = self.table.get_item(hash_key=term)
except BotoClientError as ex:
   # if partner alias does not exist then create a new entry!
     if ex.message == "Key does not exist.":
          item_old = self.table.new_item(term)
            else:
                raise ex
        item_old['partner_code'] = partner_code
        item_old['partner_name'] = partner_name
        item_old.put()