dynamodb python工具类
时间: 2023-11-22 19:50:29 浏览: 119
Python库 | mypy_boto3_dynamodb-1.17.71.post1-py3-none-any.whl
以下是使用Python操作DynamoDB的工具类示例:
```python
import boto3
class DynamoDBTool:
def __init__(self, table_name):
self.table_name = table_name
self.dynamodb = boto3.resource('dynamodb')
self.table = self.dynamodb.Table(table_name)
def put_item(self, item):
self.table.put_item(Item=item)
def get_item(self, key):
response = self.table.get_item(Key=key)
return response.get('Item')
def update_item(self, key, update_expression, expression_attribute_values):
self.table.update_item(
Key=key,
UpdateExpression=update_expression,
ExpressionAttributeValues=expression_attribute_values
)
def delete_item(self, key):
self.table.delete_item(Key=key)
```
使用示例:
```python
# 初始化工具类
dynamodb_tool = DynamoDBTool('my-table')
# 插入数据
item = {'id': '1', 'name': 'John'}
dynamodb_tool.put_item(item)
# 获取数据
key = {'id': '1'}
result = dynamodb_tool.get_item(key)
print(result)
# 更新数据
key = {'id': '1'}
update_expression = 'set #name = :new_name'
expression_attribute_values = {':new_name': 'Mike'}
dynamodb_tool.update_item(key, update_expression, expression_attribute_values)
# 删除数据
key = {'id': '1'}
dynamodb_tool.delete_item(key)
```
阅读全文