PynamoDB Attributes

0.5.1 · active · verified Fri Apr 17

pynamodb-attributes provides common custom attribute types for PynamoDB models, extending the built-in attributes with specialized types like Timestamp, Timedelta, and Protobuf Enum attributes. It aims to simplify handling complex data types in DynamoDB. The current version is 0.5.1 and it generally follows the release cadence of its upstream dependency, PynamoDB.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to define a PynamoDB model using custom attributes like `TimestampAttribute`, `TimedeltaMsAttribute`, and `IntegerSetAttribute`. It shows how to initialize an item with these types and how they would be stored and retrieved (commented out save/get operations requiring a running DynamoDB instance).

from pynamodb.models import Model
from pynamodb.attributes import UnicodeAttribute
from pynamodb_attributes import TimestampAttribute, TimedeltaMsAttribute, IntegerSetAttribute
import datetime

# Configure PynamoDB (for local DynamoDB for example)
# from pynamodb.connection import Connection
# Connection.tables = {}

class MyModel(Model):
    class Meta:
        table_name = 'my_test_model_table'
        region = 'us-east-1'
        # host = 'http://localhost:8000' # Uncomment for local DynamoDB
        read_capacity_units = 1
        write_capacity_units = 1

    id = UnicodeAttribute(hash_key=True)
    created_at = TimestampAttribute(null=True)
    processing_time = TimedeltaMsAttribute(null=True)
    favorite_numbers = IntegerSetAttribute(null=True)

# Example Usage:
if __name__ == '__main__':
    # MyModel.create_table(wait=True) # Uncomment to create table
    
    item = MyModel(
        id='item-123',
        created_at=datetime.datetime.now(datetime.timezone.utc),
        processing_time=datetime.timedelta(seconds=5, milliseconds=250),
        favorite_numbers={1, 5, 10}
    )
    # item.save() # Uncomment to save item
    
    # retrieved_item = MyModel.get('item-123') # Uncomment to retrieve item
    # print(f"Retrieved: {retrieved_item.id}, Created: {retrieved_item.created_at}, "
    #       f"Processed in: {retrieved_item.processing_time}, Favorites: {retrieved_item.favorite_numbers}")

view raw JSON →