-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdb_modules.py
71 lines (51 loc) · 1.78 KB
/
db_modules.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
import boto3
import streamlit as st
from boto3.dynamodb.conditions import Key
from dotenv import dotenv_values
config = dotenv_values(".env")
if config:
AWS_ACCESS_KEY_ID = config.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config.get('AWS_SECRET_ACCESS_KEY')
else:
AWS_ACCESS_KEY_ID = st.secrets['AWS_ACCESS_KEY_ID']
AWS_SECRET_ACCESS_KEY = st.secrets['AWS_SECRET_ACCESS_KEY']
@st.cache_resource
def get_db():
dynamodb = boto3.resource(
'dynamodb',
region_name='ap-northeast-2',
aws_access_key_id=AWS_ACCESS_KEY_ID,
aws_secret_access_key=AWS_SECRET_ACCESS_KEY,
)
print("dynamodb connected", dynamodb)
return dynamodb
def put_item(table, item):
print("item", item)
response = table.put_item(Item=item)
if response['ResponseMetadata']['HTTPStatusCode'] == 200:
print('Item successfully inserted')
else:
print('Error inserting item')
def get_item(table, item):
response = table.get_item(Key=item)
if 'Item' in response:
print('Item successfully retrieved')
return response['Item']
else:
print('Item not found')
return None
def get_lastest_item(table, name_of_partition_key, value_of_partition_key, limit_num=10):
response = table.query(
KeyConditionExpression=Key(name_of_partition_key).eq(value_of_partition_key),
ScanIndexForward=False,
Limit=limit_num
)
return response['Items']
def get_all_items(table, name_of_key):
response = table.scan()
data = response['Items']
while 'LastEvaluatedKey' in response:
response = table.scan(ExclusiveStartKey=response['LastEvaluatedKey'])
data.extend(response['Items'])
items = set(d[name_of_key] for d in data)
return items