-
Notifications
You must be signed in to change notification settings - Fork 6
/
transactions.py
313 lines (233 loc) · 9.29 KB
/
transactions.py
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
import boto3
from dynamo_pandas.serde import TypeDeserializer
from dynamo_pandas.serde import TypeSerializer
ts = TypeSerializer()
td = TypeDeserializer()
def _deserialize(items):
"""Convert dictionaries to DynamoDB format and back."""
return td.deserialize(ts.serialize(items))
def _batches(items, batch_size):
"""Split an iterable in batches."""
items = list(items)
start = 0
while start < len(items):
end = min(start + batch_size, len(items))
yield items[start:end]
start += batch_size
def get_item(*, key, table, attributes=None):
"""Get a single item from a table.
Parameters
----------
key : dict
Key of the item to get.
table : str
Name of the DynamoDB table.
attributes : list[str]
Names of the item attributes to return. If None (default), all attributes are
returned.
Returns
-------
dict, None
A dictionary representing the item's attributes. None if the key does not exist
in the table.
Examples
--------
>>> item = get_item(key={"player_id": "player_two"}, table="players")
>>> print(item)
{'bonus_points': 1,
'player_id': 'player_two',
'last_play': '2021-01-19 19:07:54',
'rating': 3.8,
'play_time': '0 days 22:07:34'}
Get only specific attributes:
>>> item = get_item(
... key={"player_id": "player_two"},
... table="players",
... attributes=["play_time", "rating"]
... )
>>> print(item)
{'rating': 3.8, 'play_time': '0 days 22:07:34'}
"""
table = boto3.resource("dynamodb").Table(table)
kwargs = {}
if attributes is not None:
kwargs["ProjectionExpression"] = ", ".join(attributes)
item = table.get_item(Key=key, **kwargs).get("Item")
return _deserialize(item)
def get_items(*, keys, table, attributes=None):
"""Get multiple items from a table.
Parameters
----------
keys : list[dict]
List of key dictionaries of the items to get.
table : str
Name of the DynamoDB table.
attributes : list[str]
Names of the item attributes to return. If None (default), all attributes are
returned.
Returns
-------
list[dict]
List of dictionaties where each dictionary represents an item's attributes.
Only items for which the key exists in the table are returned.
Examples
--------
>>> items = get_items(
... keys=[
... {"player_id": "player_two"},
... {"player_id": "player_one"},
... {"player_id": "player_five"}, # Not in the table
... ],
... table="players"
... )
>>> print(items)
[{'bonus_points': 3, 'player_id': 'player_one', 'last_play': '2021-01-18 22:47:23', 'rating': 4.3, 'play_time': '2 days 17:41:55'},
{'bonus_points': 1, 'player_id': 'player_two', 'last_play': '2021-01-19 19:07:54', 'rating': 3.8, 'play_time': '0 days 22:07:34'}]
Get only specific attributes:
>>> items = get_items(
... keys=[{"player_id": "player_two"}, {"player_id": "player_one"}],
... table="players",
... attributes=["player_id", "play_time"]
... )
>>> print(items)
[{'player_id': 'player_one', 'play_time': '2 days 17:41:55'}, {'player_id': 'player_two', 'play_time': '0 days 22:07:34'}]
""" # noqa: E501
def _request(keys, table=table, attributes=attributes):
table_dict = {"Keys": keys}
if attributes is not None:
table_dict["ProjectionExpression"] = ", ".join(attributes)
return {table: table_dict}
def _get_items(keys, table=table, attributes=attributes):
response = resource.batch_get_item(RequestItems=_request(keys))
items = response["Responses"][table]
while response["UnprocessedKeys"] != {}:
response = resource.batch_get_item(RequestItems=_request(keys))
items.extend(response["Responses"][table])
return items
resource = boto3.resource("dynamodb")
key_batches = _batches(keys, batch_size=100)
items = []
for key_batch in key_batches:
items.extend(_get_items(key_batch))
return _deserialize(items)
def get_all_items(*, table, attributes=None):
"""Get all the items in a table.
This function performs a scan of the table.
Parameters
----------
table : str
Name of the DynamoDB table.
attributes : list[str]
Names of the item attributes to return. If None (default), all attributes are
returned.
Returns
-------
list[dict]
List of dictionaties where each dictionary represents an item's attributes.
Examples
--------
>>> items = get_all_items(table="players")
>>> print(items)
[{'bonus_points': 4, 'player_id': 'player_three', 'last_play': '2021-01-21 10:22:43', 'rating': 2.5, 'play_time': '1 days 14:01:19'},
{'bonus_points': None, 'player_id': 'player_four', 'last_play': '2021-01-22 13:51:12', 'rating': 4.8, 'play_time': '0 days 03:45:49'},
{'bonus_points': 3, 'player_id': 'player_one', 'last_play': '2021-01-18 22:47:23', 'rating': 4.3, 'play_time': '2 days 17:41:55'},
{'bonus_points': 1, 'player_id': 'player_two', 'last_play': '2021-01-19 19:07:54', 'rating': 3.8, 'play_time': '0 days 22:07:34'}]
Get only specific attributes:
>>> items = get_all_items(table="players", attributes=["player_id", "play_time"])
>>> print(items)
[{'player_id': 'player_three', 'play_time': '1 days 14:01:19'},
{'player_id': 'player_four', 'play_time': '0 days 03:45:49'},
{'player_id': 'player_one', 'play_time': '2 days 17:41:55'},
{'player_id': 'player_two', 'play_time': '0 days 22:07:34'}]
""" # noqa: E501
table = boto3.resource("dynamodb").Table(table)
kwargs = {}
if attributes is not None:
kwargs["ProjectionExpression"] = ", ".join(attributes)
response = table.scan(**kwargs)
items = response["Items"]
while "LastEvaluatedKey" in response:
response = table.scan(ExclusiveStartKey=response["LastEvaluatedKey"], **kwargs)
items.extend(response["Items"])
return _deserialize(items)
def put_item(*, item, table, return_response=False):
"""Add or update an item in a table. If the item does not exist in the table it is
created, otherwise the existing item is replaced with the new one.
Item can use supported numpy or pandas data types.
Parameters
----------
item : dict
A dictionary representing the item's attributes. The item must include the
table's primary key attributes.
table : str
Name of the DynamoDB table.
return_response : bool
If True, the response from the boto3 API call will be returned.
Returns
-------
None, dict
None if ``return_response`` is False, the boto3 API call response if True.
Examples
--------
>>> print(item)
{'player_id': 'player_three',
'bonus_points': 4,
'last_play': Timestamp('2021-01-21 10:22:43+0000', tz='UTC'),
'rating': 2.5,
'play_time': Timedelta('1 days 14:01:19')}
>>> response = put_item(item=item, table="players", return_response=True)
>>> print(response["ResponseMetadata"]["HTTPStatusCode"])
200
"""
if not isinstance(item, dict):
raise TypeError("item must be a non-empty dictionary")
client = boto3.client("dynamodb")
response = client.put_item(TableName=table, Item=ts.serialize(item)["M"])
if return_response:
return response
def put_items(*, items, table):
"""Add or update multiple items in a table. If the item(s) do not exist in the
table they are created, otherwise the existing items are replaced with the new ones.
Items can use supported numpy or pandas data types.
Parameters
----------
items : list[dict]
List of dictionaries where each dictionary represents an item's attributes.
table : str
Name of the DynamoDB table.
Examples
--------
>>> pprint(items)
[{'bonus_points': 4,
'last_play': Timestamp('2021-01-21 10:22:43+0000', tz='UTC'),
'play_time': Timedelta('1 days 14:01:19'),
'player_id': 'player_three',
'rating': 2.5},
{'bonus_points': <NA>,
'last_play': Timestamp('2021-01-22 13:51:12+0000', tz='UTC'),
'play_time': Timedelta('0 days 03:45:49'),
'player_id': 'player_four',
'rating': 4.8}]
>>> put_items(items=items, table="players)
"""
if not isinstance(items, list):
raise TypeError("items must be a list of non-empty dictionaries")
def _put_items(items, table=table):
response = client.batch_write_item(
RequestItems={table: [{"PutRequest": {"Item": item}} for item in items]}
)
if response["UnprocessedItems"] != {}:
return response["UprocessedItems"][table]
else:
return []
client = boto3.client("dynamodb")
items_to_process = [i["M"] for i in ts.serialize(items)["L"]]
batch_size = 25
while len(items_to_process) > 0:
batch_items = items_to_process[:batch_size]
items_to_process = items_to_process[batch_size:]
unprocessed_items = _put_items(batch_items)
if len(unprocessed_items) > batch_size // 2:
batch_size = batch_size // 2 + 1
# Put unprocessed items at back of queue.
items_to_process.extend(unprocessed_items)