一个工具的集合,试图使AWS boto3更像Python
awspytools的Python项目详细描述
awspytools公司
发电机数据库
这是一个帮助python包,使DynamoDB更易于使用。在
首先,从awspytools导入DynamoDBDatastore:
fromawspytoolsimportDynamoDBDataStore
使用表名初始化存储:
^{pr2}$默认情况下,我们假设使用以下哈希键、排序键和索引键:
hash_key='PK'sort_key='SK'GSI1_HASH_KEY='GSI1PK'GSI1_SORT_KEY='GSI1SK'GSI1_HASH_KEY='GSI2PK'GSI2_SORT_KEY='GSI2SK'
要覆盖这些值,可以按如下方式定义存储:
store=DynamoDBDataStore(table_name='DynamoDB Table Name',hash_key='custom_hash',sort_key='custom_sort',use_default_index_keys=False)
您可以按如下方式添加自定义索引键:
store.add_index_key('custom gsi 1')
或者您可以添加多个索引键,如下所示:
store.add_index_keys(['custom gsi 1 hash','custom gsi 1 sort'])
要获取文档,请执行以下操作:
result=store.get_document(index=('hash_key','sort_key'),return_index=True)
如果指定:
return_index=False
响应对象不会在响应中指定哈希/排序键或GSI键。在
要保存文档,请执行以下操作:
store.save_document(document={"number":1,"hello":"world","foo":['bar','spam'],"foo":{"spam":"eggs"}},index=('hash_id','sort_id'))
要获取多个文档,需要提供一个查询。注意,这将为您分页结果,以便返回所有文档!在
query={'ExpressionAttributeNames':{'#PK':'PK'},'ExpressionAttributeValues':{':PK':{'S':'hash_key'}},'KeyConditionExpression':'#PK = :PK'}result=store.get_documents(query)
删除文档: 结果=store.delete_文档(索引=('hash_key','sort\u key'))
要执行批处理请求,我们有一个boto3的批处理“写入”项的包装:
batch_request=store.batch_request(request_items=[{"DeleteRequest":{...},#As per boto3's parameter structure"PutRequest":{...}#As per boto3's document structure parameter structure}])
执行事务:
transaction_items=[{'Update':{'Key':{'PK':{'S':'hash'},'SK':{'S':'sort'},},'UpdateExpression':'SET some_key = :some_value','ExpressionAttributeValues':{':some_value':{'S':'hello world'},},'TableName':store.table_name}},{'Update':{'Key':{'PK':{'S':'hash'},'SK':{'S':'sort'},},'UpdateExpression':'SET new_key = :new_value','ExpressionAttributeValues':{':new_value':{'S':'hello world'},},'TableName':store.table_name}}]store.transaction_write(transaction_items,"some_unique_id")
- 项目
标签: