-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrandom-book-from-db.py
More file actions
37 lines (29 loc) · 1007 Bytes
/
random-book-from-db.py
File metadata and controls
37 lines (29 loc) · 1007 Bytes
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
import boto3
import random
import json
from decimal import Decimal
# Custom JSON encoder to handle Decimal values
class DecimalEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Decimal):
return int(o)
return super(DecimalEncoder, self).default(o)
# Create a connection to DynamoDB Local
dynamodb = boto3.resource('dynamodb',
aws_access_key_id="dummy",
aws_secret_access_key="dummy",
region_name="local",
endpoint_url='http://localhost:8000')
# Specify the table name
table_name = 'Books'
# Get a reference to the table
table = dynamodb.Table(table_name)
# Scan the table to get all items
response = table.scan()
items = response['Items']
# Select a random book
random_book = random.choice(items)
# Convert the book to JSON
json_book = json.dumps(random_book, cls=DecimalEncoder)
# Print the JSON representation of the random book
print(json_book)