API Documentation

Top-level package for DynamoDB Mapping.

class DynamoDBMapping(table_name, boto3_session=None, **kwargs)[source]

Bases: MutableMapping

DynamoDBMapping is an alternative API for Amazon DynamoDB that implements the abstract methods of Python collections.abc.MutableMapping base class, effectively allowing you to use a DynamoDB table as if it were a Python dictionary.

You have the following options to configure the underlying boto3 session:

  • Automatic configuration: pass nothing to DynamoDBMapping initializer. This will prompt DynamoDBMapping to load the default boto3.session.Session object, which in turn will use the standard boto3 credentials chain to find AWS credentials (e.g., the ~/.aws/credentials file, environment variables, etc.).

  • Pass a preconfigured boto3.session.Session object

  • Pass aws_access_key_id and aws_secret_access_key as keyword arguments. Additionally, the optional aws_region and aws_profile arguments are also considered.

Example:

from dynamodb_mapping import DynamoDBMapping
mapping = DynamoDBMapping(table_name="my_table")

# Iterate over all items:
for key, value in mapping.items():
    print(key, value)

# Get a single item:
print(mapping["my_key"])

# Create or modify an item:
mapping["my_key"] = {"description": "foo", "price": 123}

# Delete an item:
del mapping["my_key"]

All methods that iterate over the elements of the table do so in a lazy manner, in that the successive pages of the scan operation are queried only on demand. Examples of such operations include scan, iteration over keys, iteration over values, and iteration over items (key-value tuples). You should pay particular attention to certain patterns that fetch all items in the table, for example, calling list(mapping.values()). This call will execute an exhaustive scan on your table, which can be costly, and attempt to load all items into memory, which can be resource-demanding if your table is particularly large.

The __len__ implementation of this class returns a best-effort estimate of the number of items in the table using the TableDescription DynamoDB API. The number of items are updated at DynamoDB service side approximately once in every 6 hours. If you need the exact number of items currently in the table, you can use len(list(mapping.keys())). Note however that this will cause to run an exhaustive scan operation on your table.

DynamoDB tables may be configured with a simple primary key (a partition key only) or a composite primary key (a partition key plus a sort key). If your table is configured with a simple primary key, the API of DynamoDBMapping accepts either a Python primitive type (str, bytes, bytearray, int, or Decimal) or a one-element tuple containing this single key value wherever a key value should be passed. If your table is configured with a composite primary key, the API accepts a two-elements tuple with the possible primitive key types. The DynamoDBKeySimplified type alias reflects these all these choices.

Items are returned as a Python mapping, where the keys are name of the item attributes, and the values are one of the permitted DynamoDB value types. The DynamoDBItemType type reflects the possible item types.

Warning

As of the time of the writing, the support of composite keys is untested and might not work.

Parameters:
  • table_name (str) – The name of the DynamoDB table.

  • boto3_session (Optional[boto3.session.Session]) – An optional preconfigured boto3 Session object.

  • **kwargs – Additional keyword parameters for manual configuration of the boto3 client: aws_access_key_id, aws_secret_access_key, aws_region, aws_profile.

scan(**kwargs)[source]

Performs a scan operation on the DynamoDB table. The scan is executed in a lazy manner, in that the successive pages are queried only on demand.

Example:

for item in mapping.scan():
    print(item)
Parameters:

**kwargs – keyword arguments to be passed to the underlying DynamoDB scan() operation.

Returns:

An iterator over all items in the table.

Return type:

Iterator[DynamoDBItemType]

get_item(keys, **kwargs)[source]

Retrieves a single item from the table.

The value(s) of the item’s key(s) should be specified.

This method returns a dictionary wrapper over a single item from the table. You can access the attributes of the item as if it was a common Python dictionary (i.e. with the [] operators), but the wrapper also allows you to modify directly the single attribute values of the item, as shown in the example.

Example:

my_item = mapping.get_item("my_key")
print(my_item)
my_item["title"] = "FooBar"
Parameters:
  • keys (DynamoDBKeySimplified) – The key value. This can either be a simple Python type, if only the partition key is specified in the table’s key schema, or a tuple of the partition key and the range key values, if both are specified in the key schema.

  • **kwargs – keyword arguments to be passed to the underlying DynamoDB get_item() operation.

Raises:
  • ValueError – If the required key values are not specified.

  • KeyError – If no item can be found under this key in the table.

Returns:

A dictionary wrapper over a single item from the table.

Return type:

DynamoDBItemAccessor

set_item(keys, item, **kwargs)[source]

Create or overwrite a single item in the table.

Example:

mapping.set_item("my_key", {"name": "my first object", "data": {"foo": "bar"}})
Parameters:
  • keys (DynamoDBKeySimplified) – The key value. This can either be a simple Python type, if only the partition key is specified in the table’s key schema, or a tuple of the partition key and the range key values, if both are specified in the key schema.

  • item (DynamoDBItemType) – The new item.

  • **kwargs – keyword arguments to be passed to the underlying DynamoDB set_item() operation.

Return type:

None

put_item(keys, item, **kwargs)[source]

An alias for the set_item method.

Parameters:
  • keys (DynamoDBKeySimplified) –

  • item (DynamoDBItemType) –

Return type:

None

del_item(keys, check_existing=True, **kwargs)[source]

Delete a single item from the table.

Example:

mapping.del_item("my_key")
Parameters:
  • keys (DynamoDBKeySimplified) – The key value. This can either be a simple Python type, if only the partition key is specified in the table’s key schema, or a tuple of the partition key and the range key values, if both are specified in the key schema.

  • check_existing – Raise ValueError if the specified key does not exists in the table. Defaults to True to be consistent with python dict implementation, however this causes an additional get_item operation to be executed.

  • **kwargs – keyword arguments to be passed to the underlying DynamoDB delete_item() operation.

Return type:

None

modify_item(keys, modifications, **kwargs)[source]

Modify the properties of an existing item.

Example:

mapping.modify_item("my_key", {"title": "new_title"})
Parameters:
  • keys (DynamoDBKeySimplified) – The key value of the item. This can either be a simple Python type, if only the partition key is specified in the table’s key schema, or a tuple of the partition key and the range key values, if both are specified in the key schema.

  • modifications (DynamoDBItemType) – A mapping containing the desired modifications to the fields of the item. This mapping follows the same format as the entire item, but it isn’t required to contain all fields: fields that are omitted will be unaffected. To delete a field, set the field value to None.

  • **kwargs – keyword arguments to be passed to the underlying DynamoDB update_item() operation.

Return type:

None

__iter__()[source]

Returns an iterator over the table.

This method performs a lazy DynamoDB scan operation, calling internally the scan() method.

Example:

for item in mapping:
    print(item)
Return type:

Iterator

__len__()[source]

Returns a best effort estimation of the number of items in the table.

If you need the precise number of items in the table, you can use len(list(mapping.keys())). However this later can be a costly operation.

Example:

print(len(mapping))
Return type:

int

__getitem__(key)[source]

Retrieves a single item from the table.

Delegates the call to get_item() method without additional keyword arguments.

Example:

print(mapping["my_key"])
mapping["my_key"]["info"] = "You can directly add or modify item attributes!"
Parameters:

key (Any) –

Return type:

Any

__setitem__(key, value)[source]

Creates or overwrites a single item in the table.

Delegates the call to set_item() method without additional keyword arguments.

Example:

mapping["my_key"] = {"name": "my first object", "data": {"foo": "bar"}}
Parameters:
  • key (DynamoDBKeySimplified) –

  • value (DynamoDBItemType) –

Return type:

None

__delitem__(key)[source]

Deletes a single item from the table.

Delegates the call to del_item() method without additional keyword arguments.

Example:

del mapping["my_key"]
Parameters:

key (Any) –

Return type:

None

items()[source]

Returns an efficient implementation of the ItemsView on this table.

The returned view can be used to iterate over (key, value) tuples in the table.

Example:

for key, item in mapping.items():
    print(key, item)
Returns:

The items view.

Return type:

ItemsView

values()[source]

Returns an efficient implementation of the ValuesView on this table.

The returned view can be used to iterate over the values in the table.

Example:

for item in mapping.values():
    print(item)
Returns:

The values view.

Return type:

ValuesView

keys()[source]

Returns an efficient implementation of the KeysView on this table.

The returned view can be used to iterate over the keys in the table.

Example:

for key in mapping.keys():
    print(key)
Returns:

The keys view.

Return type:

KeysView