desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Subscribe an SQS queue to a topic. This is convenience method that handles most of the complexity involved in using an SQS queue as an endpoint for an SNS topic. To achieve this the following operations are performed: * The correct ARN is constructed for the SQS queue and that ARN is then subscribed to the topic. * A...
def subscribe_sqs_queue(self, topic, queue):
t = queue.id.split('/') q_arn = queue.arn sid = hashlib.md5((topic + q_arn).encode('utf-8')).hexdigest() sid_exists = False resp = self.subscribe(topic, 'sqs', q_arn) attr = queue.get_attributes('Policy') if ('Policy' in attr): policy = json.loads(attr['Policy']) else: po...
'Get properties of a Topic :type topic: string :param topic: The ARN of the new topic. :type token: string :param token: Short-lived token sent to and endpoint during the Subscribe operation. :type authenticate_on_unsubscribe: bool :param authenticate_on_unsubscribe: Optional parameter indicating that you wish to disab...
def confirm_subscription(self, topic, token, authenticate_on_unsubscribe=False):
params = {'TopicArn': topic, 'Token': token} if authenticate_on_unsubscribe: params['AuthenticateOnUnsubscribe'] = 'true' return self._make_request('ConfirmSubscription', params)
'Allows endpoint owner to delete subscription. Confirmation message will be delivered. :type subscription: string :param subscription: The ARN of the subscription to be deleted.'
def unsubscribe(self, subscription):
params = {'SubscriptionArn': subscription} return self._make_request('Unsubscribe', params)
'Get list of all subscriptions. :type next_token: string :param next_token: Token returned by the previous call to this method.'
def get_all_subscriptions(self, next_token=None):
params = {} if next_token: params['NextToken'] = next_token return self._make_request('ListSubscriptions', params)
'Get list of all subscriptions to a specific topic. :type topic: string :param topic: The ARN of the topic for which you wish to find subscriptions. :type next_token: string :param next_token: Token returned by the previous call to this method.'
def get_all_subscriptions_by_topic(self, topic, next_token=None):
params = {'TopicArn': topic} if next_token: params['NextToken'] = next_token return self._make_request('ListSubscriptionsByTopic', params)
'The `CreatePlatformApplication` action creates a platform application object for one of the supported push notification services, such as APNS and GCM, to which devices and mobile apps may register. You must specify PlatformPrincipal and PlatformCredential attributes when using the `CreatePlatformApplication` action. ...
def create_platform_application(self, name=None, platform=None, attributes=None):
params = {} if (name is not None): params['Name'] = name if (platform is not None): params['Platform'] = platform if (attributes is not None): self._build_dict_as_list_params(params, attributes, 'Attributes') return self._make_request(action='CreatePlatformApplication', param...
'The `SetPlatformApplicationAttributes` action sets the attributes of the platform application object for the supported push notification services, such as APNS and GCM. For more information, see `Using Amazon SNS Mobile Push Notifications`_. :type platform_application_arn: string :param platform_application_arn: Platf...
def set_platform_application_attributes(self, platform_application_arn=None, attributes=None):
params = {} if (platform_application_arn is not None): params['PlatformApplicationArn'] = platform_application_arn if (attributes is not None): self._build_dict_as_list_params(params, attributes, 'Attributes') return self._make_request(action='SetPlatformApplicationAttributes', params=pa...
'The `GetPlatformApplicationAttributes` action retrieves the attributes of the platform application object for the supported push notification services, such as APNS and GCM. For more information, see `Using Amazon SNS Mobile Push Notifications`_. :type platform_application_arn: string :param platform_application_arn: ...
def get_platform_application_attributes(self, platform_application_arn=None):
params = {} if (platform_application_arn is not None): params['PlatformApplicationArn'] = platform_application_arn return self._make_request(action='GetPlatformApplicationAttributes', params=params)
'The `ListPlatformApplications` action lists the platform application objects for the supported push notification services, such as APNS and GCM. The results for `ListPlatformApplications` are paginated and return a limited list of applications, up to 100. If additional records are available after the first page result...
def list_platform_applications(self, next_token=None):
params = {} if (next_token is not None): params['NextToken'] = next_token return self._make_request(action='ListPlatformApplications', params=params)
'The `ListEndpointsByPlatformApplication` action lists the endpoints and endpoint attributes for devices in a supported push notification service, such as GCM and APNS. The results for `ListEndpointsByPlatformApplication` are paginated and return a limited list of endpoints, up to 100. If additional records are availab...
def list_endpoints_by_platform_application(self, platform_application_arn=None, next_token=None):
params = {} if (platform_application_arn is not None): params['PlatformApplicationArn'] = platform_application_arn if (next_token is not None): params['NextToken'] = next_token return self._make_request(action='ListEndpointsByPlatformApplication', params=params)
'The `DeletePlatformApplication` action deletes a platform application object for one of the supported push notification services, such as APNS and GCM. For more information, see `Using Amazon SNS Mobile Push Notifications`_. :type platform_application_arn: string :param platform_application_arn: PlatformApplicationArn...
def delete_platform_application(self, platform_application_arn=None):
params = {} if (platform_application_arn is not None): params['PlatformApplicationArn'] = platform_application_arn return self._make_request(action='DeletePlatformApplication', params=params)
'The `CreatePlatformEndpoint` creates an endpoint for a device and mobile app on one of the supported push notification services, such as GCM and APNS. `CreatePlatformEndpoint` requires the PlatformApplicationArn that is returned from `CreatePlatformApplication`. The EndpointArn that is returned when using `CreatePlatf...
def create_platform_endpoint(self, platform_application_arn=None, token=None, custom_user_data=None, attributes=None):
params = {} if (platform_application_arn is not None): params['PlatformApplicationArn'] = platform_application_arn if (token is not None): params['Token'] = token if (custom_user_data is not None): params['CustomUserData'] = custom_user_data if (attributes is not None): ...
'The `DeleteEndpoint` action, which is idempotent, deletes the endpoint from SNS. For more information, see `Using Amazon SNS Mobile Push Notifications`_. :type endpoint_arn: string :param endpoint_arn: EndpointArn of endpoint to delete.'
def delete_endpoint(self, endpoint_arn=None):
params = {} if (endpoint_arn is not None): params['EndpointArn'] = endpoint_arn return self._make_request(action='DeleteEndpoint', params=params)
'The `SetEndpointAttributes` action sets the attributes for an endpoint for a device on one of the supported push notification services, such as GCM and APNS. For more information, see `Using Amazon SNS Mobile Push Notifications`_. :type endpoint_arn: string :param endpoint_arn: EndpointArn used for SetEndpointAttribut...
def set_endpoint_attributes(self, endpoint_arn=None, attributes=None):
params = {} if (endpoint_arn is not None): params['EndpointArn'] = endpoint_arn if (attributes is not None): self._build_dict_as_list_params(params, attributes, 'Attributes') return self._make_request(action='SetEndpointAttributes', params=params)
'The `GetEndpointAttributes` retrieves the endpoint attributes for a device on one of the supported push notification services, such as GCM and APNS. For more information, see `Using Amazon SNS Mobile Push Notifications`_. :type endpoint_arn: string :param endpoint_arn: EndpointArn for GetEndpointAttributes input.'
def get_endpoint_attributes(self, endpoint_arn=None):
params = {} if (endpoint_arn is not None): params['EndpointArn'] = endpoint_arn return self._make_request(action='GetEndpointAttributes', params=params)
':type layer2: :class:`boto.dynamodb.layer2.Layer2` :param layer2: A `Layer2` api object. :type response: dict :param response: The output of `boto.dynamodb.layer1.Layer1.describe_table`.'
def __init__(self, layer2, response):
self.layer2 = layer2 self._dict = {} self.update_from_response(response)
'Create a Table object. If you know the name and schema of your table, you can create a ``Table`` object without having to make any API calls (normally an API call is made to retrieve the schema of a table). Example usage:: table = Table.create_from_schema( boto.connect_dynamodb(), \'tablename\', Schema.create(hash_key...
@classmethod def create_from_schema(cls, layer2, name, schema):
table = cls(layer2, {'Table': {'TableName': name}}) table._schema = schema return table
'Update the state of the Table object based on the response data received from Amazon DynamoDB.'
def update_from_response(self, response):
if ('Table' in response): self._dict.update(response['Table']) elif ('TableDescription' in response): self._dict.update(response['TableDescription']) if ('KeySchema' in self._dict): self._schema = Schema(self._dict['KeySchema'])
'Refresh all of the fields of the Table object by calling the underlying DescribeTable request. :type wait_for_active: bool :param wait_for_active: If True, this command will not return until the table status, as returned from Amazon DynamoDB, is \'ACTIVE\'. :type retry_seconds: int :param retry_seconds: If wait_for_ac...
def refresh(self, wait_for_active=False, retry_seconds=5):
done = False while (not done): response = self.layer2.describe_table(self.name) self.update_from_response(response) if wait_for_active: if (self.status == 'ACTIVE'): done = True else: time.sleep(retry_seconds) else: ...
'Update the ProvisionedThroughput for the Amazon DynamoDB Table. :type read_units: int :param read_units: The new value for ReadCapacityUnits. :type write_units: int :param write_units: The new value for WriteCapacityUnits.'
def update_throughput(self, read_units, write_units):
self.layer2.update_throughput(self, read_units, write_units)
'Delete this table and all items in it. After calling this the Table objects status attribute will be set to \'DELETING\'.'
def delete(self):
self.layer2.delete_table(self)
'Retrieve an existing item from the table. :type hash_key: int|long|float|str|unicode|Binary :param hash_key: The HashKey of the requested item. The type of the value must match the type defined in the schema for the table. :type range_key: int|long|float|str|unicode|Binary :param range_key: The optional RangeKey of t...
def get_item(self, hash_key, range_key=None, attributes_to_get=None, consistent_read=False, item_class=Item):
return self.layer2.get_item(self, hash_key, range_key, attributes_to_get, consistent_read, item_class)
'Checks the table to see if the Item with the specified ``hash_key`` exists. This may save a tiny bit of time/bandwidth over a straight :py:meth:`get_item` if you have no intention to touch the data that is returned, since this method specifically tells Amazon not to return anything but the Item\'s key. :type hash_key:...
def has_item(self, hash_key, range_key=None, consistent_read=False):
try: self.get_item(hash_key, range_key=range_key, attributes_to_get=[hash_key], consistent_read=consistent_read) except dynamodb_exceptions.DynamoDBKeyNotFoundError: return False return True
'Return an new, unsaved Item which can later be PUT to Amazon DynamoDB. This method has explicit (but optional) parameters for the hash_key and range_key values of the item. You can use these explicit parameters when calling the method, such as:: >>> my_item = my_table.new_item(hash_key=\'a\', range_key=1, attrs={\'ke...
def new_item(self, hash_key=None, range_key=None, attrs=None, item_class=Item):
return item_class(self, hash_key, range_key, attrs)
'Perform a query on the table. :type hash_key: int|long|float|str|unicode|Binary :param hash_key: The HashKey of the requested item. The type of the value must match the type defined in the schema for the table. :type range_key_condition: :class:`boto.dynamodb.condition.Condition` :param range_key_condition: A Conditi...
def query(self, hash_key, *args, **kw):
return self.layer2.query(self, hash_key, *args, **kw)
'Scan through this table, this is a very long and expensive operation, and should be avoided if at all possible. :type scan_filter: A dict :param scan_filter: A dictionary where the key is the attribute name and the value is a :class:`boto.dynamodb.condition.Condition` object. Valid Condition objects include: * EQ - eq...
def scan(self, *args, **kw):
return self.layer2.scan(self, *args, **kw)
'Return a set of attributes for a multiple items from a single table using their primary keys. This abstraction removes the 100 Items per batch limitations as well as the "UnprocessedKeys" logic. :type keys: list :param keys: A list of scalar or tuple values. Each element in the list represents one Item to retrieve. ...
def batch_get_item(self, keys, attributes_to_get=None):
return TableBatchGenerator(self, keys, attributes_to_get)
'Queue the addition of an attribute to an item in DynamoDB. This will eventually result in an UpdateItem request being issued with an update action of ADD when the save method is called. :type attr_name: str :param attr_name: Name of the attribute you want to alter. :type attr_value: int|long|float|set :param attr_valu...
def add_attribute(self, attr_name, attr_value):
self._updates[attr_name] = ('ADD', attr_value)
'Queue the deletion of an attribute from an item in DynamoDB. This call will result in a UpdateItem request being issued with update action of DELETE when the save method is called. :type attr_name: str :param attr_name: Name of the attribute you want to alter. :type attr_value: set :param attr_value: A set of values t...
def delete_attribute(self, attr_name, attr_value=None):
self._updates[attr_name] = ('DELETE', attr_value)
'Queue the putting of an attribute to an item in DynamoDB. This call will result in an UpdateItem request being issued with the update action of PUT when the save method is called. :type attr_name: str :param attr_name: Name of the attribute you want to alter. :type attr_value: int|long|float|str|set :param attr_value:...
def put_attribute(self, attr_name, attr_value):
self._updates[attr_name] = ('PUT', attr_value)
'Commits pending updates to Amazon DynamoDB. :type expected_value: dict :param expected_value: A dictionary of name/value pairs that you expect. This dictionary should have name/value pairs where the name is the name of the attribute and the value is either the value you are expecting or False if you expect the attrib...
def save(self, expected_value=None, return_values=None):
return self.table.layer2.update_item(self, expected_value, return_values)
'Delete the item from DynamoDB. :type expected_value: dict :param expected_value: A dictionary of name/value pairs that you expect. This dictionary should have name/value pairs where the name is the name of the attribute and the value is either the value you are expecting or False if you expect the attribute not to ex...
def delete(self, expected_value=None, return_values=None):
return self.table.layer2.delete_item(self, expected_value, return_values)
'Store a new item or completely replace an existing item in Amazon DynamoDB. :type expected_value: dict :param expected_value: A dictionary of name/value pairs that you expect. This dictionary should have name/value pairs where the name is the name of the attribute and the value is either the value you are expecting o...
def put(self, expected_value=None, return_values=None):
return self.table.layer2.put_item(self, expected_value, return_values)
'Overrwrite the setter to instead update the _updates method so this can act like a normal dict'
def __setitem__(self, key, value):
if (self._updates is not None): self.put_attribute(key, value) dict.__setitem__(self, key, value)
'Remove this key from the items'
def __delitem__(self, key):
if (self._updates is not None): self.delete_attribute(key) dict.__delitem__(self, key)
':raises: ``DynamoDBExpiredTokenError`` if the security token expires.'
def make_request(self, action, body='', object_hook=None):
headers = {'X-Amz-Target': ('%s_%s.%s' % (self.ServiceName, self.Version, action)), 'Host': self.region.endpoint, 'Content-Type': 'application/x-amz-json-1.0', 'Content-Length': str(len(body))} http_request = self.build_base_http_request('POST', '/', '/', {}, headers, body, None) start = time.time() res...
'Returns a dictionary of results. The dictionary contains a **TableNames** key whose value is a list of the table names. The dictionary could also contain a **LastEvaluatedTableName** key whose value would be the last table name returned if the complete list of table names was not returned. This value would then be p...
def list_tables(self, limit=None, start_table=None):
data = {} if limit: data['Limit'] = limit if start_table: data['ExclusiveStartTableName'] = start_table json_input = json.dumps(data) return self.make_request('ListTables', json_input)
'Returns information about the table including current state of the table, primary key schema and when the table was created. :type table_name: str :param table_name: The name of the table to describe.'
def describe_table(self, table_name):
data = {'TableName': table_name} json_input = json.dumps(data) return self.make_request('DescribeTable', json_input)
'Add a new table to your account. The table name must be unique among those associated with the account issuing the request. This request triggers an asynchronous workflow to begin creating the table. When the workflow is complete, the state of the table will be ACTIVE. :type table_name: str :param table_name: The na...
def create_table(self, table_name, schema, provisioned_throughput):
data = {'TableName': table_name, 'KeySchema': schema, 'ProvisionedThroughput': provisioned_throughput} json_input = json.dumps(data) response_dict = self.make_request('CreateTable', json_input) return response_dict
'Updates the provisioned throughput for a given table. :type table_name: str :param table_name: The name of the table to update. :type provisioned_throughput: dict :param provisioned_throughput: A Python version of the ProvisionedThroughput data structure defined by DynamoDB.'
def update_table(self, table_name, provisioned_throughput):
data = {'TableName': table_name, 'ProvisionedThroughput': provisioned_throughput} json_input = json.dumps(data) return self.make_request('UpdateTable', json_input)
'Deletes the table and all of it\'s data. After this request the table will be in the DELETING state until DynamoDB completes the delete operation. :type table_name: str :param table_name: The name of the table to delete.'
def delete_table(self, table_name):
data = {'TableName': table_name} json_input = json.dumps(data) return self.make_request('DeleteTable', json_input)
'Return a set of attributes for an item that matches the supplied key. :type table_name: str :param table_name: The name of the table containing the item. :type key: dict :param key: A Python version of the Key data structure defined by DynamoDB. :type attributes_to_get: list :param attributes_to_get: A list of attribu...
def get_item(self, table_name, key, attributes_to_get=None, consistent_read=False, object_hook=None):
data = {'TableName': table_name, 'Key': key} if attributes_to_get: data['AttributesToGet'] = attributes_to_get if consistent_read: data['ConsistentRead'] = True json_input = json.dumps(data) response = self.make_request('GetItem', json_input, object_hook=object_hook) if ('Item' n...
'Return a set of attributes for a multiple items in multiple tables using their primary keys. :type request_items: dict :param request_items: A Python version of the RequestItems data structure defined by DynamoDB.'
def batch_get_item(self, request_items, object_hook=None):
if (not request_items): return {} data = {'RequestItems': request_items} json_input = json.dumps(data) return self.make_request('BatchGetItem', json_input, object_hook=object_hook)
'This operation enables you to put or delete several items across multiple tables in a single API call. :type request_items: dict :param request_items: A Python version of the RequestItems data structure defined by DynamoDB.'
def batch_write_item(self, request_items, object_hook=None):
data = {'RequestItems': request_items} json_input = json.dumps(data) return self.make_request('BatchWriteItem', json_input, object_hook=object_hook)
'Create a new item or replace an old item with a new item (including all attributes). If an item already exists in the specified table with the same primary key, the new item will completely replace the old item. You can perform a conditional put by specifying an expected rule. :type table_name: str :param table_name:...
def put_item(self, table_name, item, expected=None, return_values=None, object_hook=None):
data = {'TableName': table_name, 'Item': item} if expected: data['Expected'] = expected if return_values: data['ReturnValues'] = return_values json_input = json.dumps(data) return self.make_request('PutItem', json_input, object_hook=object_hook)
'Edits an existing item\'s attributes. You can perform a conditional update (insert a new attribute name-value pair if it doesn\'t exist, or replace an existing name-value pair if it has certain expected attribute values). :type table_name: str :param table_name: The name of the table. :type key: dict :param key: A Pyt...
def update_item(self, table_name, key, attribute_updates, expected=None, return_values=None, object_hook=None):
data = {'TableName': table_name, 'Key': key, 'AttributeUpdates': attribute_updates} if expected: data['Expected'] = expected if return_values: data['ReturnValues'] = return_values json_input = json.dumps(data) return self.make_request('UpdateItem', json_input, object_hook=object_hook...
'Delete an item and all of it\'s attributes by primary key. You can perform a conditional delete by specifying an expected rule. :type table_name: str :param table_name: The name of the table containing the item. :type key: dict :param key: A Python version of the Key data structure defined by DynamoDB. :type expected:...
def delete_item(self, table_name, key, expected=None, return_values=None, object_hook=None):
data = {'TableName': table_name, 'Key': key} if expected: data['Expected'] = expected if return_values: data['ReturnValues'] = return_values json_input = json.dumps(data) return self.make_request('DeleteItem', json_input, object_hook=object_hook)
'Perform a query of DynamoDB. This version is currently punting and expecting you to provide a full and correct JSON body which is passed as is to DynamoDB. :type table_name: str :param table_name: The name of the table to query. :type hash_key_value: dict :param key: A DynamoDB-style HashKeyValue. :type range_key_con...
def query(self, table_name, hash_key_value, range_key_conditions=None, attributes_to_get=None, limit=None, consistent_read=False, scan_index_forward=True, exclusive_start_key=None, object_hook=None, count=False):
data = {'TableName': table_name, 'HashKeyValue': hash_key_value} if range_key_conditions: data['RangeKeyCondition'] = range_key_conditions if attributes_to_get: data['AttributesToGet'] = attributes_to_get if limit: data['Limit'] = limit if count: data['Count'] = True ...
'Perform a scan of DynamoDB. This version is currently punting and expecting you to provide a full and correct JSON body which is passed as is to DynamoDB. :type table_name: str :param table_name: The name of the table to scan. :type scan_filter: dict :param scan_filter: A Python version of the ScanFilter data structu...
def scan(self, table_name, scan_filter=None, attributes_to_get=None, limit=None, exclusive_start_key=None, object_hook=None, count=False):
data = {'TableName': table_name} if scan_filter: data['ScanFilter'] = scan_filter if attributes_to_get: data['AttributesToGet'] = attributes_to_get if limit: data['Limit'] = limit if count: data['Count'] = True if exclusive_start_key: data['ExclusiveStartK...
'Convert the Batch object into the format required for Layer1.'
def to_dict(self):
batch_dict = {} key_list = [] for key in self.keys: if isinstance(key, tuple): (hash_key, range_key) = key else: hash_key = key range_key = None k = self.table.layer2.build_key_from_values(self.table.schema, hash_key, range_key) key_list.ap...
'Convert the Batch object into the format required for Layer1.'
def to_dict(self):
op_list = [] for item in self.puts: d = {'Item': self.table.layer2.dynamize_item(item)} d = {'PutRequest': d} op_list.append(d) for key in self.deletes: if isinstance(key, tuple): (hash_key, range_key) = key else: hash_key = key ran...
'Add a Batch to this BatchList. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object in which the items are contained. :type keys: list :param keys: A list of scalar or tuple values. Each element in the list represents one Item to retrieve. If the schema for the table has both a HashKey and ...
def add_batch(self, table, keys, attributes_to_get=None, consistent_read=False):
self.append(Batch(table, keys, attributes_to_get, consistent_read))
'Resubmit the batch to get the next result set. The request object is rebuild from scratch meaning that all batch added between ``submit`` and ``resubmit`` will be lost. Note: This method is experimental and subject to changes in future releases'
def resubmit(self):
del self[:] if (not self.unprocessed): return None for (table_name, table_req) in six.iteritems(self.unprocessed): table_keys = table_req['Keys'] table = self.layer2.get_table(table_name) keys = [] for key in table_keys: h = key['HashKeyElement'] ...
'Convert a BatchList object into format required for Layer1.'
def to_dict(self):
d = {} for batch in self: b = batch.to_dict() if b['Keys']: d[batch.table.name] = b return d
'Add a BatchWrite to this BatchWriteList. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object in which the items are contained. :type puts: list of :class:`boto.dynamodb.item.Item` objects :param puts: A list of items that you want to write to DynamoDB. :type deletes: A list :param deletes: A...
def add_batch(self, table, puts=None, deletes=None):
self.append(BatchWrite(table, puts, deletes))
'Convert a BatchWriteList object into format required for Layer1.'
def to_dict(self):
d = {} for batch in self: (table_name, batch_dict) = batch.to_dict() d[table_name] = batch_dict return d
'Convenience method to create a schema object. Example usage:: schema = Schema.create(hash_key=(\'foo\', \'N\')) schema2 = Schema.create(hash_key=(\'foo\', \'N\'), range_key=(\'bar\', \'S\')) :type hash_key: tuple :param hash_key: A tuple of (hash_key_name, hash_key_type) :type range_key: tuple :param hash_key: A tuple...
@classmethod def create(cls, hash_key, range_key=None):
reconstructed = {'HashKeyElement': {'AttributeName': hash_key[0], 'AttributeType': hash_key[1]}} if (range_key is not None): reconstructed['RangeKeyElement'] = {'AttributeName': range_key[0], 'AttributeType': range_key[1]} instance = cls(None) instance._dict = reconstructed return instance
'Encodes a python type to the format expected by DynamoDB.'
def encode(self, attr):
dynamodb_type = self._get_dynamodb_type(attr) try: encoder = getattr(self, ('_encode_%s' % dynamodb_type.lower())) except AttributeError: raise ValueError(('Unable to encode dynamodb type: %s' % dynamodb_type)) return {dynamodb_type: encoder(attr)}
'Takes the format returned by DynamoDB and constructs the appropriate python type.'
def decode(self, attr):
if ((len(attr) > 1) or (not attr) or is_str(attr)): return attr dynamodb_type = list(attr.keys())[0] if (dynamodb_type.lower() == dynamodb_type): return attr try: decoder = getattr(self, ('_decode_%s' % dynamodb_type.lower())) except AttributeError: return attr re...
'The total number of items retrieved thus far. This value changes with iteration and even when issuing a call with count=True, it is necessary to complete the iteration to assert an accurate count value.'
@property def count(self):
self.response return self._count
'As above, but representing the total number of items scanned by DynamoDB, without regard to any filters.'
@property def scanned_count(self):
self.response return self._scanned_count
'Returns a float representing the ConsumedCapacityUnits accumulated.'
@property def consumed_units(self):
self.response return self._consumed_units
'The current response to the call from DynamoDB.'
@property def response(self):
return (self.next_response() if (self._response is None) else self._response)
'Issue a call and return the result. You can invoke this method while iterating over the TableGenerator in order to skip to the next "page" of results.'
def next_response(self):
limit = self.kwargs.get('limit') if ((self.remaining > 0) and ((limit is None) or (limit > self.remaining))): self.kwargs['limit'] = self.remaining self._response = self.callable(**self.kwargs) self.kwargs['limit'] = limit self._consumed_units += self._response.get('ConsumedCapacityUnits', 0...
'Use the ``decimal.Decimal`` type for encoding/decoding numeric types. By default, ints/floats are used to represent numeric types (\'N\', \'NS\') received from DynamoDB. Using the ``Decimal`` type is recommended to prevent loss of precision.'
def use_decimals(self, use_boolean=False):
self.dynamizer = (Dynamizer() if use_boolean else NonBooleanDynamizer())
'Convert a set of pending item updates into the structure required by Layer1.'
def dynamize_attribute_updates(self, pending_updates):
d = {} for attr_name in pending_updates: (action, value) = pending_updates[attr_name] if (value is None): d[attr_name] = {'Action': action} else: d[attr_name] = {'Action': action, 'Value': self.dynamizer.encode(value)} return d
'Convert a layer2 range_key_condition parameter into the structure required by Layer1.'
def dynamize_range_key_condition(self, range_key_condition):
return range_key_condition.to_dict()
'Convert a layer2 scan_filter parameter into the structure required by Layer1.'
def dynamize_scan_filter(self, scan_filter):
d = None if scan_filter: d = {} for attr_name in scan_filter: condition = scan_filter[attr_name] d[attr_name] = condition.to_dict() return d
'Convert an expected_value parameter into the data structure required for Layer1.'
def dynamize_expected_value(self, expected_value):
d = None if expected_value: d = {} for attr_name in expected_value: attr_value = expected_value[attr_name] if (attr_value is True): attr_value = {'Exists': True} elif (attr_value is False): attr_value = {'Exists': False} ...
'Convert a last_evaluated_key parameter into the data structure required for Layer1.'
def dynamize_last_evaluated_key(self, last_evaluated_key):
d = None if last_evaluated_key: hash_key = last_evaluated_key['HashKeyElement'] d = {'HashKeyElement': self.dynamizer.encode(hash_key)} if ('RangeKeyElement' in last_evaluated_key): range_key = last_evaluated_key['RangeKeyElement'] d['RangeKeyElement'] = self.dyna...
'Build a Key structure to be used for accessing items in Amazon DynamoDB. This method takes the supplied hash_key and optional range_key and validates them against the schema. If there is a mismatch, a TypeError is raised. Otherwise, a Python dict version of a Amazon DynamoDB Key data structure is returned. :type has...
def build_key_from_values(self, schema, hash_key, range_key=None):
dynamodb_key = {} dynamodb_value = self.dynamizer.encode(hash_key) if (list(dynamodb_value.keys())[0] != schema.hash_key_type): msg = ('Hashkey must be of type: %s' % schema.hash_key_type) raise TypeError(msg) dynamodb_key['HashKeyElement'] = dynamodb_value if (range_k...
'Return a new, empty :class:`boto.dynamodb.batch.BatchList` object.'
def new_batch_list(self):
return BatchList(self)
'Return a new, empty :class:`boto.dynamodb.batch.BatchWriteList` object.'
def new_batch_write_list(self):
return BatchWriteList(self)
'Return a list of the names of all tables associated with the current account and region. :type limit: int :param limit: The maximum number of tables to return.'
def list_tables(self, limit=None):
tables = [] start_table = None while ((not limit) or (len(tables) < limit)): this_round_limit = None if limit: this_round_limit = (limit - len(tables)) this_round_limit = min(this_round_limit, 100) result = self.layer1.list_tables(limit=this_round_limit, start...
'Retrieve information about an existing table. :type name: str :param name: The name of the desired table.'
def describe_table(self, name):
return self.layer1.describe_table(name)
'Create a Table object from a schema. This method will create a Table object without making any API calls. If you know the name and schema of the table, you can use this method instead of ``get_table``. Example usage:: table = layer2.table_from_schema( \'tablename\', Schema.create(hash_key=(\'foo\', \'N\'))) :type nam...
def table_from_schema(self, name, schema):
return Table.create_from_schema(self, name, schema)
'Retrieve the Table object for an existing table. :type name: str :param name: The name of the desired table. :rtype: :class:`boto.dynamodb.table.Table` :return: A Table object representing the table.'
def get_table(self, name):
response = self.layer1.describe_table(name) return Table(self, response)
'Create a new Amazon DynamoDB table. :type name: str :param name: The name of the desired table. :type schema: :class:`boto.dynamodb.schema.Schema` :param schema: The Schema object that defines the schema used by this table. :type read_units: int :param read_units: The value for ReadCapacityUnits. :type write_units: in...
def create_table(self, name, schema, read_units, write_units):
response = self.layer1.create_table(name, schema.dict, {'ReadCapacityUnits': read_units, 'WriteCapacityUnits': write_units}) return Table(self, response)
'Update the ProvisionedThroughput for the Amazon DynamoDB Table. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object whose throughput is being updated. :type read_units: int :param read_units: The new value for ReadCapacityUnits. :type write_units: int :param write_units: The new value for Wr...
def update_throughput(self, table, read_units, write_units):
response = self.layer1.update_table(table.name, {'ReadCapacityUnits': read_units, 'WriteCapacityUnits': write_units}) table.update_from_response(response)
'Delete this table and all items in it. After calling this the Table objects status attribute will be set to \'DELETING\'. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object that is being deleted.'
def delete_table(self, table):
response = self.layer1.delete_table(table.name) table.update_from_response(response)
'Create a Schema object used when creating a Table. :type hash_key_name: str :param hash_key_name: The name of the HashKey for the schema. :type hash_key_proto_value: int|long|float|str|unicode|Binary :param hash_key_proto_value: A sample or prototype of the type of value you want to use for the HashKey. Alternatively...
def create_schema(self, hash_key_name, hash_key_proto_value, range_key_name=None, range_key_proto_value=None):
hash_key = (hash_key_name, get_dynamodb_type(hash_key_proto_value)) if (range_key_name and (range_key_proto_value is not None)): range_key = (range_key_name, get_dynamodb_type(range_key_proto_value)) else: range_key = None return Schema.create(hash_key, range_key)
'Retrieve an existing item from the table. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object from which the item is retrieved. :type hash_key: int|long|float|str|unicode|Binary :param hash_key: The HashKey of the requested item. The type of the value must match the type defined in the sche...
def get_item(self, table, hash_key, range_key=None, attributes_to_get=None, consistent_read=False, item_class=Item):
key = self.build_key_from_values(table.schema, hash_key, range_key) response = self.layer1.get_item(table.name, key, attributes_to_get, consistent_read, object_hook=self.dynamizer.decode) item = item_class(table, hash_key, range_key, response['Item']) if ('ConsumedCapacityUnits' in response): it...
'Return a set of attributes for a multiple items in multiple tables using their primary keys. :type batch_list: :class:`boto.dynamodb.batch.BatchList` :param batch_list: A BatchList object which consists of a list of :class:`boto.dynamoddb.batch.Batch` objects. Each Batch object contains the information about one batch...
def batch_get_item(self, batch_list):
request_items = batch_list.to_dict() return self.layer1.batch_get_item(request_items, object_hook=self.dynamizer.decode)
'Performs multiple Puts and Deletes in one batch. :type batch_list: :class:`boto.dynamodb.batch.BatchWriteList` :param batch_list: A BatchWriteList object which consists of a list of :class:`boto.dynamoddb.batch.BatchWrite` objects. Each Batch object contains the information about one batch of objects that you wish to ...
def batch_write_item(self, batch_list):
request_items = batch_list.to_dict() return self.layer1.batch_write_item(request_items, object_hook=self.dynamizer.decode)
'Store a new item or completely replace an existing item in Amazon DynamoDB. :type item: :class:`boto.dynamodb.item.Item` :param item: The Item to write to Amazon DynamoDB. :type expected_value: dict :param expected_value: A dictionary of name/value pairs that you expect. This dictionary should have name/value pairs wh...
def put_item(self, item, expected_value=None, return_values=None):
expected_value = self.dynamize_expected_value(expected_value) response = self.layer1.put_item(item.table.name, self.dynamize_item(item), expected_value, return_values, object_hook=self.dynamizer.decode) if ('ConsumedCapacityUnits' in response): item.consumed_units = response['ConsumedCapacityUnits']...
'Commit pending item updates to Amazon DynamoDB. :type item: :class:`boto.dynamodb.item.Item` :param item: The Item to update in Amazon DynamoDB. It is expected that you would have called the add_attribute, put_attribute and/or delete_attribute methods on this Item prior to calling this method. Those queued changes a...
def update_item(self, item, expected_value=None, return_values=None):
expected_value = self.dynamize_expected_value(expected_value) key = self.build_key_from_values(item.table.schema, item.hash_key, item.range_key) attr_updates = self.dynamize_attribute_updates(item._updates) response = self.layer1.update_item(item.table.name, key, attr_updates, expected_value, return_val...
'Delete the item from Amazon DynamoDB. :type item: :class:`boto.dynamodb.item.Item` :param item: The Item to delete from Amazon DynamoDB. :type expected_value: dict :param expected_value: A dictionary of name/value pairs that you expect. This dictionary should have name/value pairs where the name is the name of the att...
def delete_item(self, item, expected_value=None, return_values=None):
expected_value = self.dynamize_expected_value(expected_value) key = self.build_key_from_values(item.table.schema, item.hash_key, item.range_key) return self.layer1.delete_item(item.table.name, key, expected=expected_value, return_values=return_values, object_hook=self.dynamizer.decode)
'Perform a query on the table. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object that is being queried. :type hash_key: int|long|float|str|unicode|Binary :param hash_key: The HashKey of the requested item. The type of the value must match the type defined in the schema for the table. :type...
def query(self, table, hash_key, range_key_condition=None, attributes_to_get=None, request_limit=None, max_results=None, consistent_read=False, scan_index_forward=True, exclusive_start_key=None, item_class=Item, count=False):
if range_key_condition: rkc = self.dynamize_range_key_condition(range_key_condition) else: rkc = None if exclusive_start_key: esk = self.build_key_from_values(table.schema, *exclusive_start_key) else: esk = None kwargs = {'table_name': table.name, 'hash_key_value': se...
'Perform a scan of DynamoDB. :type table: :class:`boto.dynamodb.table.Table` :param table: The Table object that is being scanned. :type scan_filter: A dict :param scan_filter: A dictionary where the key is the attribute name and the value is a :class:`boto.dynamodb.condition.Condition` object. Valid Condition objects ...
def scan(self, table, scan_filter=None, attributes_to_get=None, request_limit=None, max_results=None, exclusive_start_key=None, item_class=Item, count=False):
if exclusive_start_key: esk = self.build_key_from_values(table.schema, *exclusive_start_key) else: esk = None kwargs = {'table_name': table.name, 'scan_filter': self.dynamize_scan_filter(scan_filter), 'attributes_to_get': attributes_to_get, 'limit': request_limit, 'count': count, 'exclusive_...
'Return true, if the named module is a package. We need this method to get correct spec objects with Python 3.4 (see PEP451)'
def is_package(self, fullname):
return hasattr(self.__get_module(fullname), '__path__')
'Return None Required, if is_package is implemented'
def get_code(self, fullname):
self.__get_module(fullname) return None
'Resolves an endpoint for a service and region combination. :type service_name: string :param service_name: Name of the service to resolve an endpoint for (e.g., s3) :type region_name: string :param region_name: Region/endpoint name to resolve (e.g., us-east-1) if no region is provided, the first found partition-wide e...
def construct_endpoint(self, service_name, region_name=None):
raise NotImplementedError
'Lists the partitions available to the endpoint resolver. :return: Returns a list of partition names (e.g., ["aws", "aws-cn"]).'
def get_available_partitions(self):
raise NotImplementedError
'Lists the endpoint names of a particular partition. :type service_name: string :param service_name: Name of a service to list endpoint for (e.g., s3) :type partition_name: string :param partition_name: Name of the partition to limit endpoints to. (e.g., aws for the public AWS endpoints, aws-cn for AWS China endpoints,...
def get_available_endpoints(self, service_name, partition_name='aws', allow_non_regional=False):
raise NotImplementedError
':param endpoint_data: A dict of partition data.'
def __init__(self, endpoint_data):
if ('partitions' not in endpoint_data): raise ValueError('Missing "partitions" in endpoint data') self._endpoint_data = endpoint_data
'Constructs the handlers. :type host: string :param host: The host to which the request is being sent. :type config: boto.pyami.Config :param config: Boto configuration. :type provider: boto.provider.Provider :param provider: Provider details. Raises: NotReadyToAuthenticate: if this handler is not willing to authentica...
def __init__(self, host, config, provider):
pass
'Invoked to add authentication details to request. :type http_request: boto.connection.HTTPRequest :param http_request: HTTP request that needs to be authenticated.'
def add_auth(self, http_request):
pass
'Setup this class'
def setup_class(cls):
cls.objs = [] o = SimpleModel() o.name = 'Simple Object' o.strs = ['B', 'A', 'C', 'Foo'] o.num = 1 o.put() cls.objs.append(o) o2 = SimpleModel() o2.name = 'Referenced Object' o2.num = 2 o2.put() cls.objs.append(o2) o3 = SubModel() o3.name = 'Sub Object' ...
'Remove our objects'
def teardown_class(cls):
for o in cls.objs: try: o.delete() except: pass
'Test using the "Find" method'
def test_find(self):
assert (SimpleModel.find(name='Simple Object').next().id == self.objs[0].id) assert (SimpleModel.find(name='Referenced Object').next().id == self.objs[1].id) assert (SimpleModel.find(name='Sub Object').next().id == self.objs[2].id)