-
Notifications
You must be signed in to change notification settings - Fork 12
/
README.md
456 lines (332 loc) · 12.2 KB
/
README.md
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
# dyntastic
[![CI](https://github.com/nayaverdier/dyntastic/actions/workflows/ci.yml/badge.svg)](https://github.com/nayaverdier/dyntastic/actions/workflows/ci.yml)
[![codecov](https://codecov.io/gh/nayaverdier/dyntastic/branch/main/graph/badge.svg)](https://codecov.io/gh/nayaverdier/dyntastic)
[![pypi](https://img.shields.io/pypi/v/dyntastic)](https://pypi.org/project/dyntastic)
[![license](https://img.shields.io/github/license/nayaverdier/dyntastic.svg)](https://github.com/nayaverdier/dyntastic/blob/main/LICENSE)
A DynamoDB library on top of Pydantic and boto3.
## Installation
```bash
pip3 install dyntastic
```
If the Pydantic binaries are too large for you (they can exceed 90MB),
use the following:
```bash
pip3 uninstall pydantic # if pydantic is already installed
pip3 install dyntastic --no-binary pydantic
```
## Usage
The core functionality of this library is provided by the `Dyntastic` class.
`Dyntastic` is a subclass of Pydantic's `BaseModel`, so can be used in all the
same places a Pydantic model can be used (FastAPI, etc).
```python
import uuid
from datetime import datetime
from typing import Optional
from dyntastic import Dyntastic
from pydantic import Field
class Product(Dyntastic):
__table_name__ = "products"
__hash_key__ = "product_id"
product_id: str = Field(default_factory=lambda: str(uuid.uuid4()))
name: str
description: Optional[str] = None
price: float
tax: Optional[float] = None
class Event(Dyntastic):
__table_name__ = "events"
__hash_key__ = "event_id"
__range_key__ = "timestamp"
event_id: str
timestamp: datetime
data: 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 DynamoDB
Using the `Product` example from above, simply:
```python
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 DynamoDB
```python
Product.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:
```python
Event.get("d2e91c30-e701-422f-b71b-465b02749f18", "2022-02-12T18:27:55.837Z")
```
Consistent reads are supported:
```python
Event.get(..., consistent_read=True)
```
A `DoesNotExist` error is raised by `get` if a key is not found:
```python
Product.get("nonexistent")
# Traceback (most recent call last):
# ...
# dyntastic.exceptions.DoesNotExist
```
Use `safe_get` instead to return `None` if the key is not found:
```python
Product.safe_get("nonexistent")
# None
```
### Querying Items in DynamoDB
```python
# A is shorthand for the Attr class (i.e. attribute)
from dyntastic import A
# auto paging iterable
for event in Event.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 index
Event.query(A.my_other_field == 12345, index="my_other_field-index")
# note: Must provide a condition expression rather than just the value
Event.query(123545, index="my_other_field-index") # errors!
# query an index with an optional filter expression
filter_expression = None
if filter_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 read
Event.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 value
Event.query("some_event_id", range_key_condition=A.version.begins_with("2023"), scan_index_forward=False)
```
DynamoDB Indexes using a `KEYS_ONLY` or `INCLUDE` projection are supported:
```python
for event in Event.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 items
for event in Event.query("2023-09-22", index="date-keys-only-index", load_full_item=True):
event.data
# {...}
```
If you need to manually handle pagination, use `query_page`:
```python
page = Event.query_page(...)
page.items
# [...]
page.has_more
# True
page.last_evaluated_key
# {"event_id": "some_event_id", "timestamp": "..."}
Event.query_page(..., last_evaluated_key=page.last_evaluated_key)
```
### Scanning Items in DynamoDB
Scanning is done identically to querying, except there are no hash key
or range key conditions.
```python
# auto paging iterable
for event in Event.scan():
pass
Event.scan((A.my_field < 5) & (A.some_other_field.is_in(["a", "b", "c"])))
Event.scan(..., consistent_read=True)
```
### Updating Items in DynamoDB
Examples:
```python
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.set(A.my_int + 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 index
my_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"}))
# Multiple updates can be performed at once
my_item.update(
A.my_field.set("new_value"),
A.my_int.set(A.my_int + 1),
...
)
```
The data is automatically refreshed after the update request. To disable this
behavior, pass `refresh=False`:
```python
my_item.update(..., refresh=False)
```
Supports conditions:
```python
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, pass `require_condition=True`:
```python
my_item.update(..., require_condition=True)
```
### Batch Reads
Multiple items can be read from a table at the same time using the `batch_get` function.
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.
```python
MyModel.batch_get(["hash_key_1", "hash_key_2", "hash_key_3"])
# => [MyModel(...), MyModel(...)]
```
For models with a range key defined:
```python
MyModel.batch_get([("hash_key_1", "range_key_1"), ("hash_key_2", "range_key_2")])
# => [MyModel(...), MyModel(...)]
```
### Batch Writes
Save 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.
```python
with MyModel.batch_writer():
MyModel(id="0").delete()
MyModel(id="1").save()
MyModel(id="2").save()
# all operations are performed once the `with` context is exited
```
To configure a smaller batch size, for example when each item is relatively large:
```python
with MyModel.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 reached
MyModel(id="3).save()
# The final operation is performed here now that the `with` context has exited
```
### Transactions
Dyntastic supports DynamoDB transactions. Transactions are performed using the
`transaction` context manager and can be used to perform operations across one or multiple
tables that reside in the same region.
```python
from dyntastic import transaction
with transaction():
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 passing `auto_commit=True`.
For example, to commit every 50 items:
```python
with transaction(auto_commit=True, commit_every=50):
item1 = SomeTable(...)
item2 = AnotherTable.get(...)
item1.save()
item2.update(A.something.set("..."))
```
### Create a DynamoDB Table
This 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:
```python
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):
```python
# All of the following are equivalent
index1 = "my_field"
index1 = Index("my_field")
index1 = Index("my_field", index_name="my_field-index")
# Range keys are also supported
index2 = 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 names
In 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.
```python
import os
from dyntastic import Dyntastic
os.environ["MY_TABLE_NAME"] = "my_table"
class Product(Dyntastic):
__table_name__ = lambda: os.getenv("MY_TABLE_NAME")
__hash_key__ = "product_id"
product_id: str
```
## Custom dynamodb endpoint or region for local development
To 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.
```python
from dyntastic import Dyntastic
class Product(Dyntastic):
__table_name__ = "products"
__table_region__ = "us-east-1"
__table_host__ = "http://localhost:8000"
__hash_key__ = "product_id"
product_id: str
```
You can also set the environment variables `DYNTASTIC_HOST` and/or `DYNTASTIC_REGION` to 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.
```python
import os
from dyntastic import Dyntastic
os.environ["DYNTASTIC_HOST"] = "http://localhost:8000"
os.environ["DYNTASTIC_REGION"] = "us-east-1"
class Product(Dyntastic):
__table_name__ = "products"
__hash_key__ = "product_id"
product_id: str
```
## Contributing / Developer Setup
Make sure [`just`](https://github.com/casey/just) is installed on your system
To setup the dev environment and install dependencies:
```bash
# create and activate a new venv
python3 -m venv .venv
. .venv/bin/activate
# install all dev dependencies
just install-dev
# to automatically run pre-commit before all commits
pre-commit install
```
After making changes, lint all code + run tests:
```bash
just pre-commit
# or individually:
just isort
just black
just flake8
just mypy
just test
# run a specific test/tests
just test tests/test_save.py tests/test_get.py
just test tests/some_save.py::test_save_aliased_item
```