File size: 1,446 Bytes
2bf5d9d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ee57972
2bf5d9d
 
 
 
ee57972
2bf5d9d
 
 
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

import boto3
from boto3.dynamodb.conditions import Key
from dotenv import dotenv_values

config = dotenv_values(".env")

AWS_ACCESS_KEY_ID = config.get('AWS_ACCESS_KEY_ID')
AWS_SECRET_ACCESS_KEY = config.get('AWS_SECRET_ACCESS_KEY')

# AWS_ACCESS_KEY_ID = os.environ['AWS_ACCESS_KEY_ID']
# AWS_SECRET_ACCESS_KEY = os.environ['AWS_SECRET_ACCESS_KEY']


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

# put_item
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')

# get_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=True,
        Limit=limit_num
    )
    
    return response['Items']