Package: dyntastic
dyntasticA DynamoDB library on top of Pydantic and boto3.Installationpip3installdyntasticIf the Pydantic binaries are too large for you (they can exceed 90MB),
use the following:pip3uninstallpydantic# if pydantic is already installedpip3installdyntastic--no-binarypydanticUsageThe core functionality of this library is provided by theDyntasticclass.Dyntasticis a subclass of Pydantic'sBaseModel, so can be used in all the
same places a Pydantic model can be used (FastAPI, etc).importuuidfromdatetimeimportdatetimefromtypingimportOptionalfromdyntasticimportDyntasticfrompydanticimportFieldclassProduct(Dyntastic):__table_name__="products"__hash_key__="product_id"product_id:str=Field(default_factory=lambda:str(uuid.uuid4()))name:strdescription:Optional[str]=Noneprice:floattax:Optional[float]=NoneclassEvent(Dyntastic):__table_name__="events"__hash_key__="event_id"__range_key__="timestamp"event_id:strtimestamp:datetimedata:dict# All your favorite pydantic functionality still works:p=Product(name="bread",price=3.49)# Product(product_id='d2e91c30-e701-422f-b71b-465b02749f18', name='bread', description=None, price=3.49, tax=None)p.model_dump()# {'product_id': 'd2e91c30-e701-422f-b71b-465b02749f18', 'name': 'bread', 'description': None, 'price': 3.49, 'tax': None}p.model_dump_json()# '{"product_id": "d2e91c30-e701-422f-b71b-465b02749f18", "name": "bread", "description": null, "price": 3.49, "tax": null}'Inserting into DynamoDBUsing theProductexample from above, simply:product=Product(name="bread",description="Sourdough Bread",price=3.99)product.product_id# d2e91c30-e701-422f-b71b-465b02749f18# Nothing is written to DynamoDB until .save() is called:product.save()Getting Items from DynamoDBProduct.get("d2e91c30-e701-422f-b71b-465b02749f18")# Product(product_id='d2e91c30-e701-422f-b71b-465b02749f18', name='bread', description="Sourdough Bread", price=3.99, tax=None)The range key must be provided if one is defined:Event.get("d2e91c30-e701-422f-b71b-465b02749f18","2022-02-12T18:27:55.837Z")Consistent reads are supported:Event.get(...,consistent_read=True)ADoesNotExisterror is raised bygetif a key is not found:Product.get("nonexistent")# Traceback (most recent call last):#   ...# dyntastic.exceptions.DoesNotExistUsesafe_getinstead to returnNoneif the key is not found:Product.safe_get("nonexistent")# NoneQuerying Items in DynamoDB# A is shorthand for the Attr class (i.e. attribute)fromdyntasticimportA# auto paging iterableforeventinEvent.query("some_event_id"):print(event)Event.query("some_event_id",per_page=10)Event.query("some_event_id")Event.query("some_event_id",range_key_condition=A.timestamp<datetime(2022,2,13))Event.query("some_event_id",filter_condition=A.some_field=="foo")# query an indexEvent.query(A.my_other_field==12345,index="my_other_field-index")# note: Must provide a condition expression rather than just the valueEvent.query(123545,index="my_other_field-index")# errors!# query an index with an optional filter expressionfilter_expression=Noneiffilter_value:filter_expression=A('filter_field').eq(filter_value)Event.query(A.my_other_field==12345,index="my_other_field-index",filter_expression=filter_expression)# consistent readEvent.query("some_event_id",consistent_read=True)# specifies the order for index traversal, the default is ascending order# returns the results in the order in which they are stored by sort key valueEvent.query("some_event_id",range_key_condition=A.version.begins_with("2023"),scan_index_forward=False)DynamoDB Indexes using aKEYS_ONLYorINCLUDEprojection are supported:foreventinEvent.query("2023-09-22",index="date-keys-only-index"):event.id# "..."event.timestamp# datetime(...)event.data# ValueError: Dyntastic instance was loaded from a KEYS_ONLY or INCLUDE index.#             Call refresh() to load the full item, or pass load_full_item=True#             to query() or scan()# automatically fetch the full itemsforeventinEvent.query("2023-09-22",index="date-keys-only-index",load_full_item=True):event.data# {...}If you need to manually handle pagination, usequery_page:page=Event.query_page(...)page.items# [...]page.has_more# Truepage.last_evaluated_key# {"event_id": "some_event_id", "timestamp": "..."}Event.query_page(...,last_evaluated_key=page.last_evaluated_key)Scanning Items in DynamoDBScanning is done identically to querying, except there are no hash key
or range key conditions.# auto paging iterableforeventinEvent.scan():passEvent.scan((A.my_field<5)&(A.some_other_field.is_in(["a","b","c"])))Event.scan(...,consistent_read=True)Updating Items in DynamoDBExamples:my_item.update(A.my_field.set("new_value"))my_item.update(A.my_field.set(A.another_field))my_item.update(A.my_int.set(A.another_int-10))my_item.update(A.my_int.plus(1))my_item.update(A.my_list.append("new_element"))my_item.update(A.some_attribute.set_default("value_if_not_already_present"))my_item.update(A.my_field.remove())my_item.update(A.my_list.remove(2))# remove by indexmy_item.update(A.my_string_set.add("new_element"))my_item.update(A.my_string_set.add({"new_1","new_2"}))my_item.update(A.my_string_set.delete("element_to_remove"))my_item.update(A.my_string_set.delete({"remove_1","remove_2"}))The data is automatically refreshed after the update request. To disable this
behavior, passrefresh=False:my_item.update(...,refresh=False)Supports conditions:my_item.update(...,condition=A.my_field=="something")By default, if the condition is not met, the update call will be a noop.
To instead error in this situation, passrequire_condition=True:my_item.update(...,require_condition=True)Batch ReadsMultiple items can be read from a table at the same time using thebatch_getfunction.Note that DynamoDB limits the number of items that can be read at one time to
100 items or 16MB, whichever comes first.Note that if any of the provided keys are missing from dynamo, they will simply
be excluded in the result set.MyModel.batch_get(["hash_key_1","hash_key_2","hash_key_3"])# => [MyModel(...), MyModel(...)]For models with a range key defined:MyModel.batch_get([("hash_key_1","range_key_1"),("hash_key_2","range_key_2")])# => [MyModel(...), MyModel(...)]Batch WritesSave and delete operations may also be performed in batches.Note that DynamoDB limits the number of items that can be written in a single
batch to 25 items or 16MB, whichever comes first. Dyntastic will automatically
batch in chunks of 25, or less if desired.withMyModel.batch_writer():MyModel(id="0").delete()MyModel(id="1").save()MyModel(id="2").save()# all operations are performed once the `with` context is exitedTo configure a smaller batch size, for example when each item is relatively large:withMyModel.batch_writer(batch_size=2):MyModel(id="1").save()MyModel(id="2").save()# the previous two models are written immediately, since the batch size was reachedMyModel(id="3).save()# The final operation is performed here now that the `with` context has exitedTransactionsDyntastic supports DynamoDB transactions. Transactions are performed using thetransactioncontext manager and can be used to perform operations across one or multiple
tables that reside in the same region.fromdyntasticimporttransactionwithtransaction():item1=SomeTable(...)item2=AnotherTable.get(...)item1.save()item2.update(A.something.set("..."))Note that DynamoDB limits the number of items that can be written in a single
transaction to 100 items or 4MB, whichever comes first. Dyntastic can automatically
flush the transaction in chunks of 100 (or fewer if desired) by passingauto_commit=True.For example, to commit every 50 items:withtransaction(auto_commit=True,commit_every=50):item1=SomeTable(...)item2=AnotherTable.get(...)item1.save()item2.update(A.something.set("..."))Create a DynamoDB TableThis functionality is currently meant only for use in unit tests as it does not
support configuring throughput.To create a table with no secondary indexes:MyModel.create_table()# Do not wait until the table creation is complete (subsequent operations# may error if they are performed before the table creation is finished)MyModel.create_table(wait=False)To define global secondary indexes (creating local secondary indexes is not
currently supported):# All of the following are equivalentindex1="my_field"index1=Index("my_field")index1=Index("my_field",index_name="my_field-index")# Range keys are also supportedindex2=Index("my_field","my_second_field")index2=Index("my_field","my_second_field",index_name="my_field_my_second_field-index")MyModel.create_table(index1,index2)Dynamic table namesIn some circumstances you may want the table name to be defined dynamically.
This can be done by setting the__table_name__attribute to a Callable that returns the table name
from the source of your choice. In the example below, we are using an environment variable.importosfromdyntasticimportDyntasticos.environ["MY_TABLE_NAME"]="my_table"classProduct(Dyntastic):__table_name__=lambda:os.getenv("MY_TABLE_NAME")__hash_key__="product_id"product_id:strCustom dynamodb endpoint or region for local developmentTo explicitly define an AWS region or DynamoDB endpoint url (for using a local
dynamodb docker instance, for example), set__table_region__or__table_host__.
These attributes can be a string or a Callable that returns a string.fromdyntasticimportDyntasticclassProduct(Dyntastic):__table_name__="products"__table_region__="us-east-1"__table_host__="http://localhost:8000"__hash_key__="product_id"product_id:strYou can also set the environment variablesDYNTASTIC_HOSTand/orDYNTASTIC_REGIONto control the behavior
of the underlying boto3 client and resource objects.Note: if both the environment variables and the class attributes are set,
the class attributes will take precedence.importosfromdyntasticimportDyntasticos.environ["DYNTASTIC_HOST"]="http://localhost:8000"os.environ["DYNTASTIC_REGION"]="us-east-1"classProduct(Dyntastic):__table_name__="products"__hash_key__="product_id"product_id:strContributing / Developer SetupMake surejustis installed on your systemTo setup the dev environment and install dependencies:# create and activate a new venvpython3-mvenv.venv
..venv/bin/activate# install all dev dependenciesjustinstall-dev# to automatically run pre-commit before all commitspre-commitinstallAfter making changes, lint all code + run tests:justpre-commit# or individually:justisort
justblack
justflake8
justmypy
justtest# run a specific test/testsjusttesttests/test_save.pytests/test_get.py
justtesttests/some_save.py::test_save_aliased_itemChangelog0.14.0 2023-12-21Add support for__table_region__and__table_host__to be lazy callablesDefault__table_region__and__table_host__toDYNTASTIC_REGIONandDYNTASTIC_HOSTenvironment variables if not otherwise defined0.13.1 2023-11-21Fix import error when usingpydantic>=2.50.13.0 2023-11-18Add support for python3.120.13.0a1 2023-11-03Add support for pydantic v20.12.0 2023-09-22Support KEYS_ONLY and INCLUDE DynamoDB indexes0.11.0 2023-09-22Make commit limit configurable ontransaction()context manager0.11.0a2 2023-08-25Fix issue with query returning no results when using a filter with sparse matches0.11.0a1 2023-07-20Add support for transaction writes usingtransaction()context managerNo longer commit batch when an exception is raised during the batch context
manager__exit__0.10.0 2023-04-16Add support forscan_index_forwardfor specifying ascending (True) or
descending (False) traversal of the index.0.9.0 2023-04-15Add support for__table_host__for local testing0.8.2 2022-11-12Make mypy linting more strict0.8.1 2022-11-08Fixedbatch_readto support non-string hash keys0.8.0 2022-10-12Addpy.typedmarker to indicate this library ships with type hints0.7.0 2022-10-11No changes since 0.7.0a10.7.0a1 2022-10-08Change dependency version pinning to be more flexibleOnly requireimportlib_metadatafor python3.7 and earlier0.6.0 2022-09-17Added support for__table_name__being aCallable[[], str]to allow
dynamic table nameAdded support for batch reads and writesFixedconsistent_readbehavior forsafe_get(previously was always set toTrue)0.5.0 2022-05-09Added support for multiple subclasses within one table (get_modelfunction)0.4.1 2022-04-26Fixed serialization of dynamo types when using Pydantic aliases0.4.0 2022-04-26Fixed compatibility with Pydantic aliases0.3.0 2022-04-25Added support for nested attribute conditions and update expressionsFixed bug whererefresh()would cause nested Pydantic models to be
converted to dictionaries instead of loaded into their modelsAdded Pydantic aliases (models will all be dumped using pydantic'sby_alias=Trueflag).0.2.0 2022-04-23BREAKING: Accessing attributes after callingupdate(..., refresh=False)will trigger a ValueError. Read below for more information.Added built in safety for unrefreshed instances after an update. Any
attribute accesses on an instance that was updated withrefresh=Falsewill raise a ValueError. This can be fixed by callingrefresh()to get
the most up-to-date data of the item, or by callingignore_unrefreshed()to explicitly opt-in to using stale data.0.1.0 2022-02-13Initial release