Boto DynamoDb - JSONResponseError: 400 错误请求 - 非常奇怪的行为



我正在使用Boto DynamoDb2 API,我遇到了一些非常奇怪的事情。首先,我正在使用 IAM 角色进行身份验证,我将要显示的代码正在具有附加角色的 EC2 实例上运行。该角色具有完全管理权限,我确信该问题与权限无关。

我有代码可以创建一个表,然后将一个项目添加到该表。但是,我第一次put_item时,它会抛出异常,但下一次它会立即工作。这是我的 python 解释器中的一个转储:

Python 2.7.10 (default, Aug 11 2015, 23:39:10) 
[GCC 4.8.3 20140911 (Red Hat 4.8.3-9)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import boto.dynamodb2
>>> from boto.dynamodb2.table import Table
>>> from boto.dynamodb2.fields import HashKey
>>> from boto.dynamodb2.types import NUMBER
>>> 
>>> table = Table.create('myTablse',
...     schema=[HashKey('index', data_type=NUMBER)],
...     connection=boto.dynamodb2.connect_to_region('eu-west-1'))
>>> 
>>> table.put_item(data={
...     'index': 4,
...     'sequence': 'sdfsdf34rfdsa'
... })
Traceback (most recent call last):
  File "<stdin>", line 3, in <module>
  File "/home/ec2-user/fyp/venv/local/lib/python2.7/site-packages/boto/dynamodb2/table.py", line 821, in put_item
    return item.save(overwrite=overwrite)
  File "/home/ec2-user/fyp/venv/local/lib/python2.7/site-packages/boto/dynamodb2/items.py", line 455, in save
    returned = self.table._put_item(final_data, expects=expects)
  File "/home/ec2-user/fyp/venv/local/lib/python2.7/site-packages/boto/dynamodb2/table.py", line 835, in _put_item
    self.connection.put_item(self.table_name, item_data, **kwargs)
  File "/home/ec2-user/fyp/venv/local/lib/python2.7/site-packages/boto/dynamodb2/layer1.py", line 1510, in put_item
    body=json.dumps(params))
  File "/home/ec2-user/fyp/venv/local/lib/python2.7/site-packages/boto/dynamodb2/layer1.py", line 2842, in make_request
    retry_handler=self._retry_handler)
  File "/home/ec2-user/fyp/venv/local/lib/python2.7/site-packages/boto/connection.py", line 954, in _mexe
    status = retry_handler(response, i, next_sleep)
  File "/home/ec2-user/fyp/venv/local/lib/python2.7/site-packages/boto/dynamodb2/layer1.py", line 2885, in _retry_handler
    data)
boto.exception.JSONResponseError: JSONResponseError: 400 Bad Request
{u'message': u'Requested resource not found', u'__type': u'com.amazonaws.dynamodb.v20120810#ResourceNotFoundException'}
>>> table.put_item(data={
...     'index': 4,
...     'sequence': 'sdfsdf34rfdsa'
... })
True
>>> 

有人可以告诉我这里发生了什么吗?

通了。当您提交 CreateTable API 调用并返回 200 时,这并不意味着该表尚未创建或准备好用于该事项,因为一切似乎都是异步发生的。

所以基本上,你需要等到表准备好,然后才能向其中添加项目。这是我的解决方案:

 con = boto.dynamodb2.connect_to_region('eu-west-1')
table = Table.create('myTables',
    schema=[HashKey('index', data_type=NUMBER)],
    connection=con)
while True:
    try:
        r=con.describe_table('myTables')
        if r and r['Table']['TableStatus'] == 'ACTIVE':
            break
    except JSONResponseError, e:
        if 'resource not found' in e.message:
            pass
        else:
            raise
    time.sleep(1)
table.put_item(data={
    'index': 4,
    'sequence': 'sdfsdf34rfdsa'
})

希望这对其他人有所帮助!

最新更新