API Reference

Utility Methods

dynamongo.utils.is_empty(value)[source]

Determine if a value is empty.

A value is considered empty if it is None or empty string ""

dynamongo.utils.non_empty_values(d)[source]

Return a dict with empty values removed recursively

dynamongo.utils.merge_deep(destination, source)[source]

Merge dict objects recursively

dynamongo.utils.is_subclass(value, class_)[source]

Check if value is a sub class of class_

dynamongo.utils.key_proto(attr)[source]

Return associated DynamoDB attribute type

Connection

Connection borg

class dynamongo.connection.Connection(access_key_id=None, secret_access_key=None, region=None, table_prefix=None)[source]

Borg that handles access to DynamoDB.

You should never make any explicit/direct boto3.dynamodb calls by yourself except for table maintenance operations

Before making any calls, aws credentials must be set by either:

  1. calling set_config(), or

  2. setting environment variables

    • AWS_ACCESS_KEY_ID
    • AWS_SECRET_ACCESS_KEY
    • AWS_REGION_NAME
    • AWS_TABLE_PREFIX
classmethod from_env()[source]

Read config from the env

client()[source]

Return the DynamoDB client

resource()[source]

Return DynamoDB Resource

get_table(name)[source]

Return DynamoDB Table object

Model

class dynamongo.model.Model(**kwargs)[source]

Base model class with which to define custom models.

Example usage:

from dynamongo import Model
from dynamongo import IntField, StringField, EmailField

class User(Model):
    __table__ = 'users'
    __hash_key__ = 'email'

    # fields
    email = EmailField(required=True)
    name = StringField(required=True)
    year_of_birth = IntField(max_value=2018, min_value=1900)

Each custom model can declare the following class meta data variables:

__table__ (required)

The name of table to be associated with this model. This is usually prefixed with the table prefix as set in Connection. i.e, in dynamodb, the table name will appear as <table_prefix><table_name>

__hash_key__ (required)

The name of the field to be used as the Hash key for the table. NOTE: A field for the hash key MUST be declared and it must be of primitive type str|numeric

__range_key__ (optional)

The name of the field to be used as the Range key for the table. NOTE: This is Optional. However, if declared, a corresponding field MUST be declared and it must be of primitive type str|numeric

__read_units__ (optional)

The number of read units to provision for this table (default 8)

__write_units__ (optional)

The number of write units to provision for this table (default 8)

See Amazon’s developer guide for more information about provisioned throughput Capacity for Reads and Writes

classmethod keys_in(values)[source]

Convenient method to generate CompoundKeyCondition

This is useful when working with a model that has a composite primary key i.e, both hash_key and range_key

Example usage:

import datetime
from dynamongo import Model
from dynamongo import EmailField, UUIDField, DateTimeField


class Contacts(Model):
    __table__ = 'user-contacts'
    __hash_key__ = 'user_id'
    __range_key__ = 'email'

    # fields
    user_id = UUIDField(required=True)
    email = EmailField(required=True)
    created_at = DateTimeField(default=datetime.datetime.now)


# select multiple contacts for different users when you have a
# list of (user_id, email) tuples
keys = [('user_id_1', 'john@gmail.com'), ('user_id_2', 'doe@gmail.com')]
contacts = Contacts.get_many(
    Contacts.keys_in(keys)
)
classmethod table_name()[source]

Get prefixed table name

classmethod table()[source]

Get a dynamoDB Table instance for this model

classmethod create_table()[source]

Create a table that’ll be used to store instances of cls in AWS dynamoDB.

This operation should be called before any table read or write operation is undertaken

classmethod get_one(strategy)[source]

Retrieve a single item from DynamoDB according to strategy.

See Getting a single item

Returns:Instance of cls - The fetched item
classmethod get_many(strategy, descending=False, limit=None)[source]

Retrieve a multiple items from DynamoDB according to strategy.

Performs either a BatchGet, Query, or Scan depending on strategy

See Getting multiple items

Parameters:
  • strategy – See Getting multiple items
  • descending (bool) – Sort order. Items are sorted by the hash key. Items with the same hash key value are sorted by range key
  • limit (int) – The maximum number of items to get (not necessarily the number of items returned)
Returns:

list of cls

classmethod delete_one(strategy)[source]

Deletes a single item in a table. You can perform a conditional delete operation that deletes the item if it exists, or if it has an expected attribute value.

see Deleting a single item

Returns:The deleted item
classmethod delete_many(strategy)[source]

Deletes multiple items in a table.

see Deleting multiple items

Returns:BatchResult
classmethod save_one(item, overwrite=True)[source]

Creates a new item, or replaces an old item with a new item. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item overwrite specifies under what circumstances should we overwrite an existing item.

If overwrite = True, an existing item with the same primary key is replaced by the new item unconditionally. This is the default behaviour.

If overwrite = False, a ConditionalCheckFailedException is raised if there is an existing item with the same primary key

If overwrite is a conditional expression, an existing item with the same primary key is replaced by the new item if and only if the condition is met. otherwise ConditionalCheckFailedException is raised.

see Saving single item

Parameters:
  • item – the item to save. either a dict or cls
  • overwrite – This can be a bool or a condition. it defaults to True
Raises:

ConditionalCheckFailedException

Returns:

cls

classmethod save_many(items, overwrite=True)[source]

Creates or replaces multiple items. If an item that has the same primary key as the new item already exists in the specified table, the new item completely replaces the existing item overwrite specifies under what circumstances should we overwrite an existing item.

If overwrite = True, an existing item with the same primary key is replaced by the new item unconditionally. This is the default behaviour.

If overwrite = False and there is an existing item with the same primary key, the item is added on BatchResult.fail list

If overwrite is a conditional expression and an existing item with the same primary key does not meet the condition specified, then the item is added on BatchResult.fail list.

see Saving multiple items

Parameters:
  • items – a list of items to save. each item can be either a dict or cls
  • overwritebool or a condition. it defaults to True
Returns:

BatchResult

classmethod update_from_dict(item)[source]

Updates an item if and only if it exists in the db

item primary keys must be provided.

Parameters:item (dict) –
Returns:updated item
classmethod update_one(strategy, updates)[source]

Update all items in the db that satisfy condition

updates are: ‘ADD’|’PUT’|’DELETE’

Parameters:
  • strategy – Single item selection strategy
  • updates – list[Update]
Returns:

List of updated items

class dynamongo.model.BatchResult(fail=[], success=[])[source]

Batch result class

Fields

Field classes for various types of data.

class dynamongo.fields.Field[source]

Basic field from which other fields should extend. It applies no formatting by default, and should only be used in cases where data does not need to be serialized or deserialized.

Supported primitive conditions are ==, !=, <, <=, >, and >=

set_name(name, parent=None)[source]

Set name

schema names should start with a alphabetic character

in_(value)[source]

Creates a condition where the attribute is in the value,

Parameters:value (list) – The list of values that the attribute is in.
contains(value)[source]

Creates a condition where the attribute contains the value.

Parameters:value – The value the attribute contains.
begins_with(value)[source]

Creates a condition where the attribute begins with the value.

Parameters:value – The value that the attribute begins with.
exists()[source]

Creates a condition where the attribute exists.

not_exists()[source]

Creates a condition where the attribute does not exist.

between(low, high)[source]

Creates a condition where the attribute is greater than or equal to the low value and less than or equal to the high value.

Parameters:
  • low – The value that the attribute is greater than or equal to.
  • high – The value that the attribute is less than or equal to.
set(value)[source]

Set field to the given value if it does not exist otherwise update

set_if_not_exists(value)[source]

Set field to the given value if it does not exist otherwise do nothing

remove()[source]

Remove field

default

Get the default value

to_primitive(value, context=None)[source]

Convert internal data to a value safe to store in DynamoDB.

to_native(value, context=None)[source]

Convert untrusted data to a richer Python construct.

class dynamongo.fields.IntField(**kwargs)[source]

A field that validates input as an Integer

See Schematics IntType

class dynamongo.fields.FloatField(**kwargs)[source]

A field that validates input as a Float

See Schematics FloatType

class dynamongo.fields.BooleanField(**kwargs)[source]

A boolean field

See Schematics BooleanType

class dynamongo.fields.StringField(regex=None, max_length=None, min_length=None, **kwargs)[source]

A Unicode string field.

See Schematics StringType

class dynamongo.fields.EmailField(regex=None, max_length=None, min_length=None, **kwargs)[source]

A field that validates input as an E-Mail-Address

See Schematics EmailType

class dynamongo.fields.URLField(fqdn=True, verify_exists=False, **kwargs)[source]

A field that validates the input as a URL.

See Schematics URLType

class dynamongo.fields.UUIDField(**kwargs)[source]

A field that stores a valid UUID value.

See Schematics UUIDType

class dynamongo.fields.IPAddressField(regex=None, max_length=None, min_length=None, **kwargs)[source]

A field that stores a valid IPv4 or IPv6 address.

See Schematics IPAddressType

class dynamongo.fields.DateTimeField(formats=None, serialized_format=None, parser=None, tzd='allow', convert_tz=False, drop_tzinfo=False, **kwargs)[source]

A field that holds a combined date and time value.

See Schematics DateTimeType

class dynamongo.fields.DateField(formats=None, **kwargs)[source]

A field that stores and validates date values.

See Schematics DateType

class dynamongo.fields.TimedeltaField(precision='seconds', **kwargs)[source]

A field that stores and validates timedelta value

See Schematics TimedeltaType

class dynamongo.fields.ListField(field, default=[], **kwargs)[source]

A field for storing a list of items, all of which must conform to the type specified by the field parameter.

See Schematics ListType

Note: This field cannot be set to None

append(*values)[source]

Append one or more values at the end of the list

prepend(*values)[source]

Prepend one or more values at the start of the list

class dynamongo.fields.DictField(**fields)[source]

A field that stores dict values.

Accepts named parameters which must be instances of Field

primitive_type

alias of builtins.dict

native_type

alias of builtins.dict

set_name(name, parent=None)[source]

Set name

schema names should start with a alphabetic character

default

Get the default value

to_native(value, context=None)[source]

Convert untrusted data to a richer Python construct.

to_primitive(value, context=None)[source]

Convert internal data to a value safe to store in DynamoDB.

Exceptions

exception dynamongo.exceptions.ValidationError(*args, **kwargs)[source]

Exception raised when invalid data is encountered.

exception dynamongo.exceptions.ConditionalCheckFailedException[source]

Raised when saving a Model instance would overwrite something in the database and we’ve forbidden that

exception dynamongo.exceptions.ExpressionError(msg, expression)[source]

raised if some expression rules are violated

exception dynamongo.exceptions.SchemaError(msg='', name=None, value=None)[source]

SchemaError exception is raised when a schema consistency check fails.

Common consistency failure includes:

  • lacks of __table__ or __hash_key__ definitions
  • lack of corresponding field definitions for the primary keys
  • When an invalid field type is used in DictField or ListField

Conditional Expressions

Note

These classes should never be instantiated directly by the user

class dynamongo.conditions.OP[source]
class dynamongo.conditions.BaseCondition[source]

Base class for all expressions

class dynamongo.conditions.JoinCondition(left, right)[source]

Base class for joiner expressions

class dynamongo.conditions.AndCondition(left, right)[source]

Initialized by ANDing two expressions i.e, BaseCondition & BaseCondition

class dynamongo.conditions.OrCondition(left, right)[source]

Initialized by ORing two expressions i.e, BaseCondition | BaseCondition

class dynamongo.conditions.PrimitiveCondition(attr, op, value=None)[source]

Primitive expression

Update Expressions

Note

These classes should never be instantiated directly by the user

class dynamongo.updates.UpdateBuilder(type_, expression, values)[source]

Update expression builder

classmethod create(updates)[source]

Prepares update-expression & expression-attribute-values

Parameters:updates (list[Update]|tuple(Update)) – list of updates to be performed
Returns:a tuple (update-expression, expression-attribute-values)
class dynamongo.updates.Update(field, value=None)[source]

Base abstract class for update expressions

value

validated value

static placeholder()[source]

Generate a unique placeholder string

class dynamongo.updates.RemoveUpdate(field)[source]

Update to remove attributes from the db

class dynamongo.updates.SetUpdate(field, value, if_not_exists=False)[source]

Update to set an attribute to the given value

class dynamongo.updates.ListExtendUpdate(field, value, append=True)[source]

Update to append or prepend values to a list

class dynamongo.updates.AddUpdate(field, value=None)[source]

Update to perform an addition to a numeric value