API

High Level API

DynamoDB Models for PynamoDB

class pynamodb.models.BatchWrite(model: Type[_T], auto_commit: bool = True)

A class for batch writes

commit() None

Writes all of the changes that are pending

delete(del_item: _T) None

This adds del_item to the list of pending operations to be performed.

If the list currently contains 25 items, which is the DynamoDB imposed limit on a BatchWriteItem call, one of two things will happen. If auto_commit is True, a BatchWriteItem operation will be sent with the already pending operations after which put_item is appended to the (now empty) list. If auto_commit is False, ValueError is raised to indicate additional items cannot be accepted due to the DynamoDB imposed limit.

Parameters

del_item – Should be an instance of a Model to be deleted

save(put_item: _T) None

This adds put_item to the list of pending operations to be performed.

If the list currently contains 25 items, which is the DynamoDB imposed limit on a BatchWriteItem call, one of two things will happen. If auto_commit is True, a BatchWriteItem operation will be sent with the already pending writes after which put_item is appended to the (now empty) list. If auto_commit is False, ValueError is raised to indicate additional items cannot be accepted due to the DynamoDB imposed limit.

Parameters

put_item – Should be an instance of a Model to be written

class pynamodb.models.MetaModel(name, bases, namespace, discriminator=None)

Model meta class

class pynamodb.models.MetaProtocol(*args, **kwargs)
class pynamodb.models.Model(hash_key: Optional[Any] = None, range_key: Optional[Any] = None, _user_instantiated: bool = True, **attributes: Any)

Defines a PynamoDB Model

This model is backed by a table in DynamoDB. You can create the table with the create_table method.

exception DoesNotExist(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raised when an item queried does not exist

classmethod batch_get(items: Iterable[Union[Any, Iterable[Any]]], consistent_read: Optional[bool] = None, attributes_to_get: Optional[Sequence[str]] = None) Iterator[_T]

BatchGetItem for this model

Parameters

items – Should be a list of hash keys to retrieve, or a list of tuples if range keys are used.

classmethod batch_write(auto_commit: bool = True) BatchWrite[_T]

Returns a BatchWrite context manager for a batch operation.

Parameters

auto_commit – If true, the context manager will commit writes incrementally as items are written to as necessary to honor item count limits in the DynamoDB API (see BatchWrite). Regardless of the value passed here, changes automatically commit on context exit (whether successful or not).

classmethod count(hash_key: Optional[Any] = None, range_key_condition: Optional[Condition] = None, filter_condition: Optional[Condition] = None, consistent_read: bool = False, index_name: Optional[str] = None, limit: Optional[int] = None, rate_limit: Optional[float] = None) int

Provides a filtered count

Parameters
  • hash_key – The hash key to query. Can be None.

  • range_key_condition – Condition for range key

  • filter_condition – Condition used to restrict the query results

  • consistent_read – If True, a consistent read is performed

  • index_name – If set, then this index is used

  • rate_limit – If set then consumed capacity will be limited to this amount per second

classmethod create_table(wait: bool = False, read_capacity_units: Optional[int] = None, write_capacity_units: Optional[int] = None, billing_mode: Optional[str] = None, ignore_update_ttl_errors: bool = False) Any

Create the table for this model

Parameters
  • wait – If set, then this call will block until the table is ready for use

  • read_capacity_units – Sets the read capacity units for this table

  • write_capacity_units – Sets the write capacity units for this table

  • billing_mode – Sets the billing mode ‘PROVISIONED’ (default) or ‘PAY_PER_REQUEST’ for this table

delete(condition: Optional[Condition] = None, *, add_version_condition: bool = True) Any

Deletes this object from DynamoDB.

Parameters

add_version_condition – For models which have a VersionAttribute, specifies whether the item should only be deleted if its current version matches the expected one. Set to False for a ‘delete anyway’ strategy.

Raises

pynamodb.exceptions.DeleteError – If the record can not be deleted

classmethod delete_table() Any

Delete the table for this model

classmethod describe_table() Any

Returns the result of a DescribeTable operation on this model’s table

deserialize(attribute_values: Dict[str, Dict[str, Any]]) None

Deserializes a model from botocore’s DynamoDB client.

classmethod exists() bool

Returns True if this table exists, False otherwise

classmethod from_raw_data(data: Dict[str, Any]) _T

Returns an instance of this class from the raw data

Parameters

data – A serialized DynamoDB object

classmethod get(hash_key: Any, range_key: Optional[Any] = None, consistent_read: bool = False, attributes_to_get: Optional[Sequence[str]] = None) _T

Returns a single object using the provided keys

Parameters
  • hash_key – The hash key of the desired item

  • range_key – The range key of the desired item, only used when appropriate.

  • consistent_read

  • attributes_to_get

Raises

ModelInstance.DoesNotExist – if the object to be updated does not exist

classmethod query(hash_key: Any, range_key_condition: Optional[Condition] = None, filter_condition: Optional[Condition] = None, consistent_read: bool = False, index_name: Optional[str] = None, scan_index_forward: Optional[bool] = None, limit: Optional[int] = None, last_evaluated_key: Optional[Dict[str, Dict[str, Any]]] = None, attributes_to_get: Optional[Iterable[str]] = None, page_size: Optional[int] = None, rate_limit: Optional[float] = None) ResultIterator[_T]

Provides a high level query API

Parameters
  • hash_key – The hash key to query

  • range_key_condition – Condition for range key

  • filter_condition – Condition used to restrict the query results

  • consistent_read – If True, a consistent read is performed

  • index_name – If set, then this index is used

  • limit – Used to limit the number of results returned

  • scan_index_forward – If set, then used to specify the same parameter to the DynamoDB API. Controls descending or ascending results

  • last_evaluated_key – If set, provides the starting point for query.

  • attributes_to_get – If set, only returns these elements

  • page_size – Page size of the query to DynamoDB

  • rate_limit – If set then consumed capacity will be limited to this amount per second

refresh(consistent_read: bool = False) None

Retrieves this object’s data from dynamodb and syncs this local object

Parameters
  • consistent_read – If True, then a consistent read is performed.

  • settings – per-operation settings

Raises

ModelInstance.DoesNotExist – if the object to be updated does not exist

save(condition: Optional[Condition] = None, *, add_version_condition: bool = True) Dict[str, Any]

Save this object to dynamodb

classmethod scan(filter_condition: Optional[Condition] = None, segment: Optional[int] = None, total_segments: Optional[int] = None, limit: Optional[int] = None, last_evaluated_key: Optional[Dict[str, Dict[str, Any]]] = None, page_size: Optional[int] = None, consistent_read: Optional[bool] = None, index_name: Optional[str] = None, rate_limit: Optional[float] = None, attributes_to_get: Optional[Sequence[str]] = None) ResultIterator[_T]

Iterates through all items in the table

Parameters
  • filter_condition – Condition used to restrict the scan results

  • segment – If set, then scans the segment

  • total_segments – If set, then specifies total segments

  • limit – Used to limit the number of results returned

  • last_evaluated_key – If set, provides the starting point for scan.

  • page_size – Page size of the scan to DynamoDB

  • consistent_read – If True, a consistent read is performed

  • index_name – If set, then this index is used

  • rate_limit – If set then consumed capacity will be limited to this amount per second

  • attributes_to_get – If set, specifies the properties to include in the projection expression

serialize(null_check: bool = True) Dict[str, Dict[str, Any]]

Serializes a model for botocore’s DynamoDB client.

Warning

BINARY and BINARY_SET attributes (whether top-level or nested) serialization would contain bytes objects which are not JSON-serializable by the json module.

Use to_dynamodb_dict() and to_simple_dict() for JSON-serializable mappings.

update(actions: List[Action], condition: Optional[Condition] = None, *, add_version_condition: bool = True) Any

Updates an item using the UpdateItem operation.

Parameters
  • actions – a list of Action updates to apply

  • condition – an optional Condition on which to update

  • settings – per-operation settings

  • add_version_condition – For models which have a VersionAttribute, specifies whether only to update if the version matches the model that is currently loaded. Set to False for a ‘last write wins’ strategy. Regardless, the version will always be incremented to prevent “rollbacks” by concurrent save() calls.

Raises
classmethod update_ttl(ignore_update_ttl_errors: bool) None

Attempt to update the TTL on the table. Certain implementations (eg: dynalite) do not support updating TTLs and will fail.

PynamoDB attributes

class pynamodb.attributes.Attribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)

An attribute of a model or an index.

Parameters
  • hash_key – If True, this attribute is a model’s or an index’s hash key (partition key).

  • range_key – If True, this attribute is a model’s or an index’s range key (sort key).

  • null

    If True, a None value would be considered valid and would result in the attribute not being set in the underlying DynamoDB item. If False (default), an exception will be raised when the attribute is persisted with a None value.

    Note

    This is different from pynamodb.attributes.NullAttribute, which manifests in a NULL-typed DynamoDB attribute value.

  • default

    A default value that will be assigned in new models (when they are initialized) and existing models (when they are loaded).

    Note

    Starting with PynamoDB 6.0, the default must be either an immutable value (of one of the built-in immutable types) or a callable. This prevents a common class of errors caused by unintentionally mutating the default value. A simple workaround is to pass an initializer (e.g. change default={} to default=dict) or wrap in a lambda (e.g. change default={'foo': 'bar'} to default=lambda: {'foo': 'bar'}).

  • default_for_new

    Like default, but used only for new models. Use this to assign a default for new models that you don’t want to apply to existing models when they are loaded and then re-saved.

    Note

    Starting with PynamoDB 6.0, the default must be either an immutable value (of one of the built-in immutable types) or a callable.

  • attr_name

    The name that is used for the attribute in the underlying DynamoDB item; use this to assign a “pythonic” name that is different from the persisted name, i.e.

    number_of_threads = NumberAttribute(attr_name='thread_count')
    

deserialize(value: Any) Any

Deserializes a value from botocore’s DynamoDB client.

For a list of DynamoDB attribute types and their matching botocore Python types, see DynamoDB.Client.get_item API reference.

serialize(value: Any) Any

Serializes a value for botocore’s DynamoDB client.

For a list of DynamoDB attribute types and their matching botocore Python types, see DynamoDB.Client.get_item API reference.

class pynamodb.attributes.AttributeContainer(_user_instantiated: bool = True, **attributes: Attribute)

Base class for models and maps.

from_dynamodb_dict(d: Dict[str, Dict[str, Any]]) None

Sets attributes from a mapping previously produced by to_dynamodb_dict().

from_simple_dict(d: Dict[str, Any]) None

Sets attributes from a mapping previously produced by to_simple_dict().

classmethod get_attributes() Dict[str, Attribute]

Returns the attributes of this class as a mapping from python_attr_name => attribute.

to_dynamodb_dict() Dict[str, Dict[str, Any]]

Returns the contents of this instance as a JSON-serializable mapping, where each attribute is represented as a mapping with the attribute type as the key and the attribute value as the value, e.g.

{
    "id": {
        "N": "12345"
    },
    "name": {
        "S": "Alice"
    },
}

This matches the structure of the “DynamoDB” JSON mapping in the AWS Console.

to_simple_dict(*, force: bool = False) Dict[str, Any]

Returns the contents of this instance as a simple JSON-serializable mapping.

{
    "id": 12345,
    "name": "Alice",
}

This matches the structure of the “normal” JSON mapping in the AWS Console.

Note

This representation is limited: by default, it cannot represent binary or set attributes, as their encoded form is indistinguishable from a string or list attribute respectively (and therefore ambiguous).

Parameters

force – If True, force the conversion even if the model contains Binary or Set attributes If False, a ValueError will be raised if such attributes are set.

class pynamodb.attributes.BinaryAttribute(*args: Any, legacy_encoding: bool, **kwargs: Any)

An attribute containing a binary data object (bytes).

Parameters

legacy_encoding

If True, inefficient legacy encoding will be used to maintain compatibility with PynamoDB 5 and lower. Set to False for new tables and models, and always set to False within MapAttribute.

For more details, see Upgrading Binary(Set)Attribute.

deserialize(value)

Deserializes a value from botocore’s DynamoDB client.

For a list of DynamoDB attribute types and their matching botocore Python types, see DynamoDB.Client.get_item API reference.

serialize(value)

Serializes a value for botocore’s DynamoDB client.

For a list of DynamoDB attribute types and their matching botocore Python types, see DynamoDB.Client.get_item API reference.

class pynamodb.attributes.BinarySetAttribute(*args: Any, legacy_encoding: bool, **kwargs: Any)

An attribute containing a set of binary data objects (bytes).

Parameters

legacy_encoding

If True, inefficient legacy encoding will be used to maintain compatibility with PynamoDB 5 and lower. Set to False for new tables and models, and always set to False within MapAttribute.

For more details, see Upgrading Binary(Set)Attribute.

deserialize(value)

Returns a set of decoded byte strings from base64 encoded values.

serialize(value)

Returns a list of base64 encoded binary strings. Encodes empty sets as “None”.

class pynamodb.attributes.BooleanAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)

A class for boolean attributes

deserialize(value)

Deserializes a value from botocore’s DynamoDB client.

For a list of DynamoDB attribute types and their matching botocore Python types, see DynamoDB.Client.get_item API reference.

serialize(value)

Serializes a value for botocore’s DynamoDB client.

For a list of DynamoDB attribute types and their matching botocore Python types, see DynamoDB.Client.get_item API reference.

class pynamodb.attributes.DiscriminatorAttribute(attr_name: Optional[str] = None)
deserialize(value)

Returns the class corresponding to the given discriminator value.

serialize(value)

Returns the discriminator value corresponding to the given class.

class pynamodb.attributes.DynamicMapAttribute(**attributes)

A map attribute that supports declaring attributes (like an AttributeContainer) but will also store any other values that are set on it (like a raw MapAttribute).

>>> class MyDynamicMapAttribute(DynamicMapAttribute):
>>>     a_date_time = UTCDateTimeAttribute()  # raw map attributes cannot serialize/deserialize datetime values
>>>
>>> dynamic_map = MyDynamicMapAttribute()
>>> dynamic_map.a_date_time = datetime.utcnow()
>>> dynamic_map.a_number = 5
>>> dynamic_map.serialize()  # {'a_date_time': {'S': 'xxx'}, 'a_number': {'N': '5'}}
deserialize(values)

Decode as a dict.

serialize(values, *, null_check: bool = True)

Serializes a value for botocore’s DynamoDB client.

For a list of DynamoDB attribute types and their matching botocore Python types, see DynamoDB.Client.get_item API reference.

class pynamodb.attributes.JSONAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)

A JSON Attribute

Encodes JSON to unicode internally

deserialize(value)

Deserializes JSON

serialize(value) Optional[str]

Serializes JSON to unicode

class pynamodb.attributes.ListAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[Any, Callable[[...], Any]]] = None, attr_name: Optional[str] = None, of: Optional[Type[_T]] = None)
deserialize(values)

Decode from list of AttributeValue types.

serialize(values, *, null_check: bool = True)

Encode the given list of objects into a list of AttributeValue types.

class pynamodb.attributes.MapAttribute(**attributes)

A Map Attribute

The MapAttribute class can be used to store a JSON document as “raw” name-value pairs, or it can be subclassed and the document fields represented as class attributes using Attribute instances.

To support the ability to subclass MapAttribute and use it as an AttributeContainer, instances of MapAttribute behave differently based both on where they are instantiated and on their type. Because of this complicated behavior, a bit of an introduction is warranted.

Models that contain a MapAttribute define its properties using a class attribute on the model. For example, below we define “MyModel” which contains a MapAttribute “my_map”:

class MyModel(Model):

my_map = MapAttribute(attr_name=”dynamo_name”, default=dict)

When instantiated in this manner (as a class attribute of an AttributeContainer class), the MapAttribute class acts as an instance of the Attribute class. The instance stores data about the attribute (in this example the dynamo name and default value), and acts as a data descriptor, storing any value bound to it on the attribute_values dictionary of the containing instance (in this case an instance of MyModel).

Unlike other Attribute types, the value that gets bound to the containing instance is a new instance of MapAttribute, not an instance of the primitive type. For example, a UnicodeAttribute stores strings in the attribute_values of the containing instance; a MapAttribute does not store a dict but instead stores a new instance of itself. This difference in behavior is necessary when subclassing MapAttribute in order to access the Attribute data descriptors that represent the document fields.

For example, below we redefine “MyModel” to use a subclass of MapAttribute as “my_map”:

class MyMapAttribute(MapAttribute):

my_internal_map = MapAttribute()

class MyModel(Model):

my_map = MyMapAttribute(attr_name=”dynamo_name”, default = {})

In order to set the value of my_internal_map on an instance of MyModel we need the bound value for “my_map” to be an instance of MapAttribute so that it acts as a data descriptor:

MyModel().my_map.my_internal_map = {‘foo’: ‘bar’}

That is the attribute access of “my_map” must return a MyMapAttribute instance and not a dict.

When an instance is used in this manner (bound to an instance of an AttributeContainer class), the MapAttribute class acts as an AttributeContainer class itself. The instance does not store data about the attribute, and does not act as a data descriptor. The instance stores name-value pairs in its internal attribute_values dictionary.

Thus while MapAttribute multiply inherits from Attribute and AttributeContainer, a MapAttribute instance does not behave as both an Attribute AND an AttributeContainer. Rather an instance of MapAttribute behaves EITHER as an Attribute OR as an AttributeContainer, depending on where it was instantiated.

So, how do we create this dichotomous behavior? All MapAttribute instances are initialized as AttributeContainers only. During construction of AttributeContainer classes (subclasses of MapAttribute and Model), any instances that are class attributes are transformed from AttributeContainers to Attributes (via the _make_attribute method call).

deserialize(values)

Decode as a dict.

serialize(values, *, null_check: bool = True)

Serializes a value for botocore’s DynamoDB client.

For a list of DynamoDB attribute types and their matching botocore Python types, see DynamoDB.Client.get_item API reference.

class pynamodb.attributes.NullAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)
deserialize(value)

Deserializes a value from botocore’s DynamoDB client.

For a list of DynamoDB attribute types and their matching botocore Python types, see DynamoDB.Client.get_item API reference.

serialize(value)

Serializes a value for botocore’s DynamoDB client.

For a list of DynamoDB attribute types and their matching botocore Python types, see DynamoDB.Client.get_item API reference.

class pynamodb.attributes.NumberAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)

A number attribute

deserialize(value)

Decode numbers from JSON

serialize(value)

Encode numbers as JSON

class pynamodb.attributes.NumberSetAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)

A number set attribute

deserialize(value)

Returns a set from a JSON list of numbers.

serialize(value)

Encodes a set of numbers as a JSON list. Encodes empty sets as “None”.

class pynamodb.attributes.TTLAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)

A time-to-live attribute that signifies when the item expires and can be automatically deleted. It can be assigned with a timezone-aware datetime value (for absolute expiry time) or a timedelta value (for expiry relative to the current time), but always reads as a UTC datetime value.

deserialize(value)

Deserializes a timestamp (Unix time) as a UTC datetime.

serialize(value)

Serializes a datetime as a timestamp (Unix time).

class pynamodb.attributes.UTCDateTimeAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)

An attribute for storing a UTC Datetime

deserialize(value)

Takes a UTC datetime string and returns a datetime object

serialize(value)

Takes a datetime object and returns a string

class pynamodb.attributes.UnicodeAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)

A unicode attribute

class pynamodb.attributes.UnicodeSetAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)

A unicode set

deserialize(value)

Returns a set from a list of strings.

serialize(value)

Returns a list of strings. Encodes empty sets as “None”.

class pynamodb.attributes.VersionAttribute(hash_key: bool = False, range_key: bool = False, null: Optional[bool] = None, default: Optional[Union[_T, Callable[[...], _T]]] = None, default_for_new: Optional[Union[Any, Callable[[...], _T]]] = None, attr_name: Optional[str] = None)

A number attribute that implements optimistic locking.

deserialize(value)

Decode numbers from JSON and cast to int.

serialize(value)

Cast value to int then encode as JSON

PynamoDB Indexes

class pynamodb.indexes.AllProjection

An ALL projection

class pynamodb.indexes.GlobalSecondaryIndex

A global secondary index

class pynamodb.indexes.IncludeProjection(non_attr_keys: Optional[List[str]] = None)

An INCLUDE projection

class pynamodb.indexes.Index

Base class for secondary indexes

count(hash_key: Any, range_key_condition: Optional[Condition] = None, filter_condition: Optional[Condition] = None, consistent_read: bool = False, limit: Optional[int] = None, rate_limit: Optional[float] = None) int

Count on an index

query(hash_key: Any, range_key_condition: Optional[Condition] = None, filter_condition: Optional[Condition] = None, consistent_read: bool = False, scan_index_forward: Optional[bool] = None, limit: Optional[int] = None, last_evaluated_key: Optional[Dict[str, Dict[str, Any]]] = None, attributes_to_get: Optional[List[str]] = None, page_size: Optional[int] = None, rate_limit: Optional[float] = None) ResultIterator[_M]

Queries an index

scan(filter_condition: Optional[Condition] = None, segment: Optional[int] = None, total_segments: Optional[int] = None, limit: Optional[int] = None, last_evaluated_key: Optional[Dict[str, Dict[str, Any]]] = None, page_size: Optional[int] = None, consistent_read: Optional[bool] = None, rate_limit: Optional[float] = None, attributes_to_get: Optional[List[str]] = None) ResultIterator[_M]

Scans an index

class pynamodb.indexes.KeysOnlyProjection

Keys only projection

class pynamodb.indexes.LocalSecondaryIndex

A local secondary index

class pynamodb.indexes.Projection

A class for presenting projections

class pynamodb.transactions.TransactGet(*args: Any, **kwargs: Any)
get(model_cls: Type[_M], hash_key: Any, range_key: Optional[Any] = None) _ModelFuture[_M]

Adds the operation arguments for an item to list of models to get returns a _ModelFuture object as a placeholder

Parameters
  • model_cls

  • hash_key

  • range_key

Returns

class pynamodb.transactions.TransactWrite(client_request_token: Optional[str] = None, return_item_collection_metrics: Optional[str] = None, **kwargs: Any)
class pynamodb.transactions.Transaction(connection: Connection, return_consumed_capacity: Optional[str] = None)

Base class for a type of transaction operation

class pynamodb.pagination.PageIterator(operation: Callable, args: Any, kwargs: Dict[str, Any], rate_limit: Optional[float] = None)

PageIterator handles Query and Scan result pagination.

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.Pagination.html https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.Pagination

class pynamodb.pagination.RateLimiter(rate_limit: float, time_module: Optional[Any] = None)

RateLimiter limits operations to a pre-set rate of units/seconds

Example:
Initialize a RateLimiter with the desired rate

rate_limiter = RateLimiter(rate_limit)

Now, every time before calling an operation, call acquire()

rate_limiter.acquire()

And after an operation, update the number of units consumed

rate_limiter.consume(units)

acquire() None

Sleeps the appropriate amount of time to follow the rate limit restriction

Returns

None

consume(units: int) None

Records the amount of units consumed.

Parameters

units – Number of units consumed

Returns

None

property rate_limit: float

A limit of units per seconds

class pynamodb.pagination.ResultIterator(operation: Callable, args: Any, kwargs: Dict[str, Any], map_fn: Optional[Callable] = None, limit: Optional[int] = None, rate_limit: Optional[float] = None)

ResultIterator handles Query and Scan item pagination.

https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Query.Pagination.html https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/Scan.html#Scan.Pagination

Low Level API

PynamoDB lowest level connection

class pynamodb.connection.Connection(region: Optional[str] = None, host: Optional[str] = None, read_timeout_seconds: Optional[float] = None, connect_timeout_seconds: Optional[float] = None, max_retry_attempts: Optional[int] = None, max_pool_connections: Optional[int] = None, extra_headers: Optional[Mapping[str, str]] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str] = None)

A higher level abstraction over botocore

add_meta_table(meta_table: MetaTable) None

Adds information about the table’s schema.

batch_get_item(table_name: str, keys: Sequence[str], consistent_read: Optional[bool] = None, return_consumed_capacity: Optional[str] = None, attributes_to_get: Optional[Any] = None) Dict

Performs the batch get item operation

batch_write_item(table_name: str, put_items: Optional[Any] = None, delete_items: Optional[Any] = None, return_consumed_capacity: Optional[str] = None, return_item_collection_metrics: Optional[str] = None) Dict

Performs the batch_write_item operation

property client: BotocoreBaseClientPrivate

Returns a botocore dynamodb client

create_table(table_name: str, attribute_definitions: Optional[Any] = None, key_schema: Optional[Any] = None, read_capacity_units: Optional[int] = None, write_capacity_units: Optional[int] = None, global_secondary_indexes: Optional[Any] = None, local_secondary_indexes: Optional[Any] = None, stream_specification: Optional[Dict] = None, billing_mode: str = 'PROVISIONED', tags: Optional[Dict[str, str]] = None) Dict

Performs the CreateTable operation

delete_item(table_name: str, hash_key: str, range_key: Optional[str] = None, condition: Optional[Condition] = None, return_values: Optional[str] = None, return_consumed_capacity: Optional[str] = None, return_item_collection_metrics: Optional[str] = None) Dict

Performs the DeleteItem operation and returns the result

delete_table(table_name: str) Dict

Performs the DeleteTable operation

describe_table(table_name: str) Dict

Performs the DescribeTable operation

dispatch(operation_name: str, operation_kwargs: Dict) Dict

Dispatches operation_name with arguments operation_kwargs

Raises TableDoesNotExist if the specified table does not exist

get_attribute_type(table_name: str, attribute_name: str, value: Optional[Any] = None) str

Returns the proper attribute type for a given attribute name :param value: The attribute value an be supplied just in case the type is already included

get_consumed_capacity_map(return_consumed_capacity: str) Dict

Builds the consumed capacity map that is common to several operations

get_exclusive_start_key_map(table_name: str, exclusive_start_key: str) Dict

Builds the exclusive start key attribute map

get_identifier_map(table_name: str, hash_key: str, range_key: Optional[str] = None, key: str = 'Key') Dict

Builds the identifier map that is common to several operations

get_item(table_name: str, hash_key: str, range_key: Optional[str] = None, consistent_read: bool = False, attributes_to_get: Optional[Any] = None) Dict

Performs the GetItem operation and returns the result

get_item_attribute_map(table_name: str, attributes: Any, item_key: str = 'Item', pythonic_key: bool = True) Dict

Builds up a dynamodb compatible AttributeValue map

get_item_collection_map(return_item_collection_metrics: str) Dict

Builds the item collection map

get_meta_table(table_name: str) MetaTable

Returns information about the table’s schema.

get_return_values_map(return_values: str) Dict

Builds the return values map that is common to several operations

get_return_values_on_condition_failure_map(return_values_on_condition_failure: str) Dict

Builds the return values map that is common to several operations

list_tables(exclusive_start_table_name: Optional[str] = None, limit: Optional[int] = None) Dict

Performs the ListTables operation

parse_attribute(attribute: Any, return_type: bool = False) Any

Returns the attribute value, where the attribute can be a raw attribute value, or a dictionary containing the type: {‘S’: ‘String value’}

put_item(table_name: str, hash_key: str, range_key: Optional[str] = None, attributes: Optional[Any] = None, condition: Optional[Condition] = None, return_values: Optional[str] = None, return_consumed_capacity: Optional[str] = None, return_item_collection_metrics: Optional[str] = None) Dict

Performs the PutItem operation and returns the result

query(table_name: str, hash_key: str, range_key_condition: Optional[Condition] = None, filter_condition: Optional[Any] = None, attributes_to_get: Optional[Any] = None, consistent_read: bool = False, exclusive_start_key: Optional[Any] = None, index_name: Optional[str] = None, limit: Optional[int] = None, return_consumed_capacity: Optional[str] = None, scan_index_forward: Optional[bool] = None, select: Optional[str] = None) Dict

Performs the Query operation and returns the result

scan(table_name: str, filter_condition: Optional[Any] = None, attributes_to_get: Optional[Any] = None, limit: Optional[int] = None, return_consumed_capacity: Optional[str] = None, exclusive_start_key: Optional[str] = None, segment: Optional[int] = None, total_segments: Optional[int] = None, consistent_read: Optional[bool] = None, index_name: Optional[str] = None) Dict

Performs the scan operation

property session: Session

Returns a valid botocore session

transact_get_items(get_items: Sequence[Dict], return_consumed_capacity: Optional[str] = None) Dict

Performs the TransactGet operation and returns the result

transact_write_items(condition_check_items: Sequence[Dict], delete_items: Sequence[Dict], put_items: Sequence[Dict], update_items: Sequence[Dict], client_request_token: Optional[str] = None, return_consumed_capacity: Optional[str] = None, return_item_collection_metrics: Optional[str] = None) Dict

Performs the TransactWrite operation and returns the result

update_item(table_name: str, hash_key: str, range_key: Optional[str] = None, actions: Optional[Sequence[Action]] = None, condition: Optional[Condition] = None, return_consumed_capacity: Optional[str] = None, return_item_collection_metrics: Optional[str] = None, return_values: Optional[str] = None) Dict

Performs the UpdateItem operation

update_table(table_name: str, read_capacity_units: Optional[int] = None, write_capacity_units: Optional[int] = None, global_secondary_index_updates: Optional[Any] = None) Dict

Performs the UpdateTable operation

update_time_to_live(table_name: str, ttl_attribute_name: str) Dict

Performs the UpdateTimeToLive operation

class pynamodb.connection.TableConnection(table_name: str, region: Optional[str] = None, host: Optional[str] = None, connect_timeout_seconds: Optional[float] = None, read_timeout_seconds: Optional[float] = None, max_retry_attempts: Optional[int] = None, max_pool_connections: Optional[int] = None, extra_headers: Optional[Mapping[str, str]] = None, aws_access_key_id: Optional[str] = None, aws_secret_access_key: Optional[str] = None, aws_session_token: Optional[str] = None, *, meta_table: Optional[MetaTable] = None)

A higher level abstraction over botocore

batch_get_item(keys: Sequence[str], consistent_read: Optional[bool] = None, return_consumed_capacity: Optional[str] = None, attributes_to_get: Optional[Any] = None) Dict

Performs the batch get item operation

batch_write_item(put_items: Optional[Any] = None, delete_items: Optional[Any] = None, return_consumed_capacity: Optional[str] = None, return_item_collection_metrics: Optional[str] = None) Dict

Performs the batch_write_item operation

create_table(attribute_definitions: Optional[Any] = None, key_schema: Optional[Any] = None, read_capacity_units: Optional[int] = None, write_capacity_units: Optional[int] = None, global_secondary_indexes: Optional[Any] = None, local_secondary_indexes: Optional[Any] = None, stream_specification: Optional[Dict] = None, billing_mode: str = 'PROVISIONED', tags: Optional[Dict[str, str]] = None) Dict

Performs the CreateTable operation and returns the result

delete_item(hash_key: str, range_key: Optional[str] = None, condition: Optional[Condition] = None, return_values: Optional[str] = None, return_consumed_capacity: Optional[str] = None, return_item_collection_metrics: Optional[str] = None) Dict

Performs the DeleteItem operation and returns the result

delete_table() Dict

Performs the DeleteTable operation and returns the result

describe_table() Dict

Performs the DescribeTable operation and returns the result

get_item(hash_key: str, range_key: Optional[str] = None, consistent_read: bool = False, attributes_to_get: Optional[Any] = None) Dict

Performs the GetItem operation and returns the result

get_meta_table() MetaTable

Returns a MetaTable

put_item(hash_key: str, range_key: Optional[str] = None, attributes: Optional[Any] = None, condition: Optional[Condition] = None, return_values: Optional[str] = None, return_consumed_capacity: Optional[str] = None, return_item_collection_metrics: Optional[str] = None) Dict

Performs the PutItem operation and returns the result

query(hash_key: str, range_key_condition: Optional[Condition] = None, filter_condition: Optional[Any] = None, attributes_to_get: Optional[Any] = None, consistent_read: bool = False, exclusive_start_key: Optional[Any] = None, index_name: Optional[str] = None, limit: Optional[int] = None, return_consumed_capacity: Optional[str] = None, scan_index_forward: Optional[bool] = None, select: Optional[str] = None) Dict

Performs the Query operation and returns the result

scan(filter_condition: Optional[Any] = None, attributes_to_get: Optional[Any] = None, limit: Optional[int] = None, return_consumed_capacity: Optional[str] = None, segment: Optional[int] = None, total_segments: Optional[int] = None, exclusive_start_key: Optional[str] = None, consistent_read: Optional[bool] = None, index_name: Optional[str] = None) Dict

Performs the scan operation

update_item(hash_key: str, range_key: Optional[str] = None, actions: Optional[Sequence[Action]] = None, condition: Optional[Condition] = None, return_consumed_capacity: Optional[str] = None, return_item_collection_metrics: Optional[str] = None, return_values: Optional[str] = None) Dict

Performs the UpdateItem operation

update_table(read_capacity_units: Optional[int] = None, write_capacity_units: Optional[int] = None, global_secondary_index_updates: Optional[Any] = None) Dict

Performs the UpdateTable operation and returns the result

update_time_to_live(ttl_attr_name: str) Dict

Performs the UpdateTimeToLive operation and returns the result

Exceptions

exception pynamodb.exceptions.PynamoDBException(msg: Optional[str] = None, cause: Optional[Exception] = None)

Base class for all PynamoDB exceptions.

property cause_response_code: Optional[str]

The DynamoDB response code such as:

  • ConditionalCheckFailedException

  • ProvisionedThroughputExceededException

  • TransactionCanceledException

Inspect this value to determine the cause of the error and handle it.

property cause_response_message: Optional[str]

The human-readable description of the error returned by DynamoDB.

exception pynamodb.exceptions.PynamoDBConnectionError(msg: Optional[str] = None, cause: Optional[Exception] = None)

A base class for connection errors

exception pynamodb.exceptions.DeleteError(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raised when an error occurs deleting an item

exception pynamodb.exceptions.QueryError(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raised when queries fail

exception pynamodb.exceptions.ScanError(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raised when a scan operation fails

exception pynamodb.exceptions.PutError(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raised when an item fails to be created

exception pynamodb.exceptions.UpdateError(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raised when an item fails to be updated

exception pynamodb.exceptions.GetError(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raised when an item fails to be retrieved

exception pynamodb.exceptions.TableError(msg: Optional[str] = None, cause: Optional[Exception] = None)

An error involving a dynamodb table operation

exception pynamodb.exceptions.TableDoesNotExist(table_name: str)

Raised when an operation is attempted on a table that doesn’t exist

exception pynamodb.exceptions.DoesNotExist(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raised when an item queried does not exist

exception pynamodb.exceptions.TransactWriteError(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raised when a TransactWrite operation fails.

property cancellation_reasons: List[Optional[CancellationReason]]

When cause_response_code is TransactionCanceledException, this property lists cancellation reasons in the same order as the transaction items (one-to-one). Items which were not part of the reason for cancellation would have None as the value.

For a list of possible cancellation reasons and their semantics, see TransactWriteItems in the AWS documentation.

exception pynamodb.exceptions.TransactGetError(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raised when a TransactGet operation fails.

property cancellation_reasons: List[Optional[CancellationReason]]

When cause_response_code is TransactionCanceledException, this property lists cancellation reasons in the same order as the transaction items (one-to-one). Items which were not part of the reason for cancellation would have None as the value.

For a list of possible cancellation reasons and their semantics, see TransactGetItems in the AWS documentation.

exception pynamodb.exceptions.InvalidStateError(msg: Optional[str] = None, cause: Optional[Exception] = None)

Raises when the internal state of an operation context is invalid.

exception pynamodb.exceptions.AttributeDeserializationError(attr_name: str, attr_type: str)

Raised when attribute type is invalid during deserialization.

exception pynamodb.exceptions.AttributeNullError(attr_name: str)

Raised when an attribute which is not nullable (null=False) is unset during serialization.

class pynamodb.exceptions.CancellationReason(code: str, message: Optional[str] = None, raw_item: Optional[Dict[str, Dict[str, Any]]] = None)

A reason for a transaction cancellation.

For a list of possible cancellation reasons and their semantics, see TransactGetItems and TransactWriteItems in the AWS documentation.