boto3 dynamodb 入门使用
2017-02-26 22:49
411 查看
介绍
Amazon DynamoDB 是一项快速灵活的 NoSQL 数据库服务,适合所有需要一致性且延迟低于 10 毫秒的任意规模的应用程序。它是完全托管的云数据库,支持文档和键值存储模型。灵活的数据模型和可靠的性能使其成为移动、Web、游戏、广告技术、物联网和众多其他应用的不二之选。
定价
官方网站的价格介绍:https://aws.amazon.com/cn/dynamodb/pricing/
但是我实际开发的时候一个月只有4000多写收了27RMB,我一共创建了两个表,没有搞清怎么收费,还是每个表有一个最低收费。我配置每张表的读取,写入的速度,可以根据每张表的实际使用读写和写入速度,这样可以最大的降低费用,避免不必要的浪费。
入门视频
介绍: https://aws.amazon.com/cn/dynamodb/getting-started/
上手实验营:https://aws.amazon.com/cn/dynamodb/getting-started/
代码例子
创建新表
添加新item
跟新item
我写的一个项目,对象dynamodb:
注意:
Dynamodb的保留字段,在创建表的字段的时候不要使用一下字段不然的话,在进行表操作会报错:
Dynamodb 保留字段:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html
参考文档:
官方文档: http://boto3.readthedocs.io/en/latest/guide/dynamodb.html
Amazon DynamoDB 是一项快速灵活的 NoSQL 数据库服务,适合所有需要一致性且延迟低于 10 毫秒的任意规模的应用程序。它是完全托管的云数据库,支持文档和键值存储模型。灵活的数据模型和可靠的性能使其成为移动、Web、游戏、广告技术、物联网和众多其他应用的不二之选。
定价
官方网站的价格介绍:https://aws.amazon.com/cn/dynamodb/pricing/
但是我实际开发的时候一个月只有4000多写收了27RMB,我一共创建了两个表,没有搞清怎么收费,还是每个表有一个最低收费。我配置每张表的读取,写入的速度,可以根据每张表的实际使用读写和写入速度,这样可以最大的降低费用,避免不必要的浪费。
入门视频
介绍: https://aws.amazon.com/cn/dynamodb/getting-started/
上手实验营:https://aws.amazon.com/cn/dynamodb/getting-started/
代码例子
创建新表
import boto3 # Get the service resource. dynamodb = boto3.resource('dynamodb') # Create the DynamoDB table. table = dynamodb.create_table( TableName='users', KeySchema=[ { 'AttributeName': 'username', 'KeyType': 'HASH' }, { 'AttributeName': 'last_name', 'KeyType': 'RANGE' } ], AttributeDefinitions=[ { 'AttributeName': 'username', 'AttributeType': 'S' }, { 'AttributeName': 'last_name', 'AttributeType': 'S' }, ], ProvisionedThroughput={ 'ReadCapacityUnits': 5, 'WriteCapacityUnits': 5 } ) # Wait until the table exists. table.meta.client.get_waiter('table_exists').wait(TableName='users') # Print out some data about the table. print(table.item_count)
添加新item
table.put_item( Item={ 'username': 'janedoe', 'first_name': 'Jane', 'last_name': 'Doe', 'age': 25, 'account_type': 'standard_user', } )
跟新item
table.update_item( Key={ 'username': 'janedoe', 'last_name': 'Doe' }, UpdateExpression='SET age = :val1', ExpressionAttributeValues={ ':val1': 26 } )
我写的一个项目,对象dynamodb:
# coding:utf-8 from boto3 import Session from error import DynamodbConnectionError, DynamoDBError from botocore.exceptions import ClientError from boto3.dynamodb.conditions import Attr from helper import DecimalEncoder import logging import json logger = logging.getLogger(__name__) class MyserviceDynamodb(object): """ """ def __init__(self, **kwargs): self.region = kwargs['region'] self.access_key = kwargs['access_key'] self.secret_key = kwargs['secret_key'] self.session = self.__session() def __session(self): try: session = Session(aws_access_key_id=self.access_key, aws_secret_access_key=self.secret_key,region_name=self.region) except: raise DynamodbConnectionError("Failed to connect session in region{0}".format(self.region)) return session def get_table(self, table_name): dynamodb = self.session.resource('dynamodb') if not dynamodb: raise DynamodbConnectionError("Failed to get resource for dynamodb!") try: table = dynamodb.Table(table_name) except Exception as e: logger.error("Failed to get table {0}, error".format(table_name, e)) return table def put_item(self, table, item_dict=None): try: response = table.put_item(Item=item_dict) except Exception as e: logger.error("Failed to put item in to {0}:error{1}".format(table,e)) return response def status_scan_items(self, table, event_status=None): try: response = table.scan(FilterExpression=Attr('event_status').eq(event_status)) except Exception as e: logger.error('{0} failed query items , error{1}'.format(json.dumps(table, indent=4,cls=DecimalEncoder),e)) return response def get_item(self, table, id): try: response = table.get_item(Key={'event_id': id}) except ClientError as e: if e.response['Error']['Code'] == "ConditionalCheckFailedException": logger.error(e.response['Error']['Message']) else: raise DynamoDBError('Failed to get item from dynamodb not by Conditional') else: logger.info(json.dumps(response, indent=4, cls=DecimalEncoder)) return response def update_status_by_event_id(self, table, event_id, change_status=None): try: response = table.update_item( Key = {'event_id':event_id},UpdateExpression = "SET event_status = :val1", ExpressionAttributeValues={':val1':change_status},ReturnValues="UPDATED_NEW") except ClientError as e: if e.response['Error']['Code'] == "ConditionalCheckFailedException": logger.error(e.response['Error']['Message']) else: raise DynamoDBError('Failed update the dynamodb by event_id,not Failed Conditional') else: logger.info("UpdateItem succeeded:{0}".format(json.dumps(response, indent=4, cls=DecimalEncoder))) return response
注意:
Dynamodb的保留字段,在创建表的字段的时候不要使用一下字段不然的话,在进行表操作会报错:
Attribute name is a reserved keyword; reserved keyword: status
Dynamodb 保留字段:
http://docs.aws.amazon.com/amazondynamodb/latest/developerguide/ReservedWords.html
参考文档:
官方文档: http://boto3.readthedocs.io/en/latest/guide/dynamodb.html
相关文章推荐
- 入门计划->使用(C++库)ifstream读文件数据
- JSP开发入门(一)----安装好你的机器来使用JSP
- Eclipse使用入门(3)
- Asp.Net 使用 GDI+ 绘制3D饼图入门篇源码
- Toad 使用快速入门
- Eclipse使用入门(一)
- PHP-Web应用程序开发:使用模板(入门)
- Eclipse使用入门
- .Net中的反射使用入门
- 使用DriverStudio开发WDM设备驱动程序入门
- ClearCase使用入门--step by step(序)
- Eclipse入门:使用指南
- Eclipse使用入门(2)
- .Net中的反射使用入门
- Apache和Tomcat结合使用入门
- 入门计划->使用(C++库)ofstream写文件数据
- ClearCase使用入门--step by step(管理篇)
- Ibatis2.0使用说明(一)——入门实例篇[原]
- Eclipse使用入门(三)
- .Net中的反射使用入门