[DE 프로젝트: 음악 추천 챗봇 'Sixpotify'] 3. AWS DynamoDB

NoSQL

파티션

  • 데이터 관리 및 파티션 등 다양한 이유로 데이터를 나누는 일이다.

스크린샷 2021-10-04 04 02 26

버티컬(Vertical) 파티션

  • 버티컬 파티션은 테이블을 더 작은 테이블로 나누는 작업으로써 노멀라이제이션(Normalization) 후에도 경우에 따라 컬럼을 나누는 파티션 작업을 한다.

스크린샷 2021-10-04 04 10 26

호리젠탈(Horizontal) 파티션

  • 스키마나 스트럭쳐 자체를 복사하여 데이터를 샤딩 키(Sharded Key)로 분리한다.

스크린샷 2021-10-04 04 10 54

DynamoDB

AWS 테이블 생성

스크린샷 2021-10-04 14 37 33

연결 및 저장

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
import sys
import os
import boto3
import requests
import base64
import json
import psycopg2
import logging

client_id = ""
client_secret = ""

host = "spotify2.cjwptwa04yyi.ap-northeast-2.rds.amazonaws.com"
port = 5432
username = "sixmini"
database = "postgres"
password = ""


def main():


    try:
        dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-2', endpoint_url='http://dynamodb.ap-northeast-2.amazonaws.com')
    except:
        logging.error('could not connect to dynamodb')
        sys.exit(1)

    try:
        conn = psycopg2.connect(
            host=host,
            database=database,
            user=username,
            password=password)
        cursor = conn.cursor()
    except:
        logging.error("could not connect to rds")
        sys.exit(1)

    headers = get_headers(client_id, client_secret)

    table = dynamodb.Table('top_tracks')

    cursor.execute('SELECT id FROM artists')

    countries = ['US', 'CA']
    for country in countries:
        for (artist_id, ) in cursor.fetchall():

            
            URL = "https://api.spotify.com/v1/artists/{}/top-tracks".format(artist_id)
            params = {
                'country': 'US'
            }

            r = requests.get(URL, params=params, headers=headers)

            raw = json.loads(r.text)

            for track in raw['tracks']:

                data = {
                    'artist_id': artist_id,
                    'country': country
                }

                data.update(track)

                table.put_item(
                    Item=data
                )





def get_headers(client_id, client_secret):

    endpoint = "https://accounts.spotify.com/api/token"
    encoded = base64.b64encode("{}:{}".format(client_id, client_secret).encode('utf-8')).decode('ascii')

    headers = {
        "Authorization": "Basic {}".format(encoded)
    }

    payload = {
        "grant_type": "client_credentials"
    }

    r = requests.post(endpoint, data=payload, headers=headers)

    access_token = json.loads(r.text)['access_token']

    headers = {
        "Authorization": "Bearer {}".format(access_token)
    }

    return headers


if __name__=='__main__':
    main()

스크린샷 2021-10-04 15 27 29

데이터 불러오기

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

import sys
import os
import boto3
import logging

from boto3.dynamodb.conditions import Key, Attr

def main():

    try:
        dynamodb = boto3.resource('dynamodb', region_name='ap-northeast-2', endpoint_url='http://dynamodb.ap-northeast-2.amazonaws.com')
    except:
        logging.error('could not connect to dynamodb')
        sys.exit(1)

    table = dynamodb.Table('top_tracks')

    response = table.scan(
        FilterExpression=Attr('popularity').gt(90)
    )
    print(response['Items'])
    print(len(response['Items']))



if __name__=='__main__':
    main()

'''
[
   {
      "is_playable":true,
      "duration_ms":"Decimal(""191013"")",
      "external_ids":{
         "isrc":"USUG12101839"
      },
      "uri":"spotify:track:37BZB0z9T8Xu7U3e65qxFy",
      "country":"US",
      "name":"Save Your Tears (with Ariana Grande) (Remix)",
      "album":{
         "total_tracks":"Decimal(""1"")",
         "images":[
            {
               "width":"Decimal(""640"")",
               "url":"https://i.scdn.co/image/ab67616d0000b273c6af5ffa661a365b77df6ef6",
               "height":"Decimal(""640"")"
            },
            {
               "width":"Decimal(""300"")",
               "url":"https://i.scdn.co/image/ab67616d00001e02c6af5ffa661a365b77df6ef6",
               "height":"Decimal(""300"")"
            },
            {
               "width":"Decimal(""64"")",
               "url":"https://i.scdn.co/image/ab67616d00004851c6af5ffa661a365b77df6ef6",
               "height":"Decimal(""64"")"
            }
         ],
         "artists":[
            {
               "name":"The Weeknd",
               "href":"https://api.spotify.com/v1/artists/1Xyo4u8uXC1ZmMpatF05PJ",
               "id":"1Xyo4u8uXC1ZmMpatF05PJ",
               "type":"artist",
               "external_urls":{
                  "spotify":"https://open.spotify.com/artist/1Xyo4u8uXC1ZmMpatF05PJ"
               },
               "uri":"spotify:artist:1Xyo4u8uXC1ZmMpatF05PJ"
            },
            {
               "name":"Ariana Grande",
               "href":"https://api.spotify.com/v1/artists/66CXWjxzNUsdJxJ2JdwvnR",
               "id":"66CXWjxzNUsdJxJ2JdwvnR",
               "type":"artist",
               "external_urls":{
                  "spotify":"https://open.spotify.com/artist/66CXWjxzNUsdJxJ2JdwvnR"
               },
               "uri":"spotify:artist:66CXWjxzNUsdJxJ2JdwvnR"
            }
         ],
         "release_date":"2021-04-23",
         "name":"Save Your Tears (Remix)",
         "album_type":"single",
         "release_date_precision":"day",
         "href":"https://api.spotify.com/v1/albums/2fyOpT5c9kxR8zbDh6UtXh",
         "id":"2fyOpT5c9kxR8zbDh6UtXh",
         "type":"album",
         "external_urls":{
            "spotify":"https://open.spotify.com/album/2fyOpT5c9kxR8zbDh6UtXh"
         },
         "uri":"spotify:album:2fyOpT5c9kxR8zbDh6UtXh"
      },
      "popularity":"Decimal(""91"")",
      "artists":[
         {
            "name":"The Weeknd",
            "href":"https://api.spotify.com/v1/artists/1Xyo4u8uXC1ZmMpatF05PJ",
            "id":"1Xyo4u8uXC1ZmMpatF05PJ",
            "type":"artist",
            "external_urls":{
               "spotify":"https://open.spotify.com/artist/1Xyo4u8uXC1ZmMpatF05PJ"
            },
            "uri":"spotify:artist:1Xyo4u8uXC1ZmMpatF05PJ"
         },
         {
            "name":"Ariana Grande",
            "href":"https://api.spotify.com/v1/artists/66CXWjxzNUsdJxJ2JdwvnR",
            "id":"66CXWjxzNUsdJxJ2JdwvnR",
            "type":"artist",
            "external_urls":{
               "spotify":"https://open.spotify.com/artist/66CXWjxzNUsdJxJ2JdwvnR"
            },
            "uri":"spotify:artist:66CXWjxzNUsdJxJ2JdwvnR"
         }
      ],
      "disc_number":"Decimal(""1"")",
      "href":"https://api.spotify.com/v1/tracks/37BZB0z9T8Xu7U3e65qxFy",
      "track_number":"Decimal(""1"")",
      "external_urls":{
         "spotify":"https://open.spotify.com/track/37BZB0z9T8Xu7U3e65qxFy"
      },
      "artist_id":"66CXWjxzNUsdJxJ2JdwvnR",
      "preview_url":"None",
      "is_local":false,
      "id":"37BZB0z9T8Xu7U3e65qxFy",
      "explicit":false,
      "type":"track"
   },
   {
      "is_playable":true,
      "duration_ms":"Decimal(""164441"")",
      "external_ids":{
         "isrc":"QM6MZ2156864"
      },
      "uri":"spotify:track:2bgTY4UwhfBYhGT4HUYStN",
      "country":"US",
      "name":"Butter",
      "album":{
         "total_tracks":"Decimal(""5"")",
         "images":[
            {
               "width":"Decimal(""640"")",
               "url":"https://i.scdn.co/image/ab67616d0000b2736bb2b8231817c8d205d07fb2",
               "height":"Decimal(""640"")"
            },
            {
               "width":"Decimal(""300"")",
               "url":"https://i.scdn.co/image/ab67616d00001e026bb2b8231817c8d205d07fb2",
               "height":"Decimal(""300"")"
            },
            {
               "width":"Decimal(""64"")",
               "url":"https://i.scdn.co/image/ab67616d000048516bb2b8231817c8d205d07fb2",
               "height":"Decimal(""64"")"
            }
         ],
         "artists":[
            {
               "name":"BTS",
               "href":"https://api.spotify.com/v1/artists/3Nrfpe0tUJi4K4DXYWgMUX",
               "id":"3Nrfpe0tUJi4K4DXYWgMUX",
               "type":"artist",
               "external_urls":{
                  "spotify":"https://open.spotify.com/artist/3Nrfpe0tUJi4K4DXYWgMUX"
               },
               "uri":"spotify:artist:3Nrfpe0tUJi4K4DXYWgMUX"
            }
         ],
         "release_date":"2021-06-04",
         "name":"Butter (Hotter, Sweeter, Cooler)",
         "album_type":"single",
         "release_date_precision":"day",
         "href":"https://api.spotify.com/v1/albums/1HnJKmB4P6Z8RBdLMWx18w",
         "id":"1HnJKmB4P6Z8RBdLMWx18w",
         "type":"album",
         "external_urls":{
            "spotify":"https://open.spotify.com/album/1HnJKmB4P6Z8RBdLMWx18w"
         },
         "uri":"spotify:album:1HnJKmB4P6Z8RBdLMWx18w"
      },
      "popularity":"Decimal(""91"")",
      "artists":[
         {
            "name":"BTS",
            "href":"https://api.spotify.com/v1/artists/3Nrfpe0tUJi4K4DXYWgMUX",
            "id":"3Nrfpe0tUJi4K4DXYWgMUX",
            "type":"artist",
            "external_urls":{
               "spotify":"https://open.spotify.com/artist/3Nrfpe0tUJi4K4DXYWgMUX"
            },
            "uri":"spotify:artist:3Nrfpe0tUJi4K4DXYWgMUX"
         }
      ],
      "disc_number":"Decimal(""1"")",
      "href":"https://api.spotify.com/v1/tracks/2bgTY4UwhfBYhGT4HUYStN",
      "track_number":"Decimal(""1"")",
      "external_urls":{
         "spotify":"https://open.spotify.com/track/2bgTY4UwhfBYhGT4HUYStN"
      },
      "artist_id":"3Nrfpe0tUJi4K4DXYWgMUX",
      "preview_url":"https://p.scdn.co/mp3-preview/edf24f427483d886b640c5ed9944f9291e0976fc?cid=74cbd487458843f1ad3f5fa1e914c02f",
      "is_local":false,
      "id":"2bgTY4UwhfBYhGT4HUYStN",
      "explicit":false,
      "type":"track"
   },
   {
      "is_playable":true,
      "duration_ms":"Decimal(""228000"")",
      "external_ids":{
         "isrc":"GBAYE2100952"
      },
      "uri":"spotify:track:3FeVmId7tL5YN8B7R3imoM",
      "country":"US",
      "name":"My Universe",
      "album":{
         "total_tracks":"Decimal(""2"")",
         "images":[
            {
               "width":"Decimal(""640"")",
               "url":"https://i.scdn.co/image/ab67616d0000b2733ed6dca44a955dbe1c06d8fc",
               "height":"Decimal(""640"")"
            },
            {
               "width":"Decimal(""300"")",
               "url":"https://i.scdn.co/image/ab67616d00001e023ed6dca44a955dbe1c06d8fc",
               "height":"Decimal(""300"")"
            },
            {
               "width":"Decimal(""64"")",
               "url":"https://i.scdn.co/image/ab67616d000048513ed6dca44a955dbe1c06d8fc",
               "height":"Decimal(""64"")"
            }
         ],
         "artists":[
            {
               "name":"Coldplay",
               "href":"https://api.spotify.com/v1/artists/4gzpq5DPGxSnKTe4SA8HAU",
               "id":"4gzpq5DPGxSnKTe4SA8HAU",
               "type":"artist",
               "external_urls":{
                  "spotify":"https://open.spotify.com/artist/4gzpq5DPGxSnKTe4SA8HAU"
               },
               "uri":"spotify:artist:4gzpq5DPGxSnKTe4SA8HAU"
            },
            {
               "name":"BTS",
               "href":"https://api.spotify.com/v1/artists/3Nrfpe0tUJi4K4DXYWgMUX",
               "id":"3Nrfpe0tUJi4K4DXYWgMUX",
               "type":"artist",
               "external_urls":{
                  "spotify":"https://open.spotify.com/artist/3Nrfpe0tUJi4K4DXYWgMUX"
               },
               "uri":"spotify:artist:3Nrfpe0tUJi4K4DXYWgMUX"
            }
         ],
         "release_date":"2021-09-24",
         "name":"My Universe",
         "album_type":"single",
         "release_date_precision":"day",
         "href":"https://api.spotify.com/v1/albums/39McjovZ3M6n5SFtNmWTdp",
         "id":"39McjovZ3M6n5SFtNmWTdp",
         "type":"album",
         "external_urls":{
            "spotify":"https://open.spotify.com/album/39McjovZ3M6n5SFtNmWTdp"
         },
         "uri":"spotify:album:39McjovZ3M6n5SFtNmWTdp"
      },
      "popularity":"Decimal(""91"")",
      "artists":[
         {
            "name":"Coldplay",
            "href":"https://api.spotify.com/v1/artists/4gzpq5DPGxSnKTe4SA8HAU",
            "id":"4gzpq5DPGxSnKTe4SA8HAU",
            "type":"artist",
            "external_urls":{
               "spotify":"https://open.spotify.com/artist/4gzpq5DPGxSnKTe4SA8HAU"
            },
            "uri":"spotify:artist:4gzpq5DPGxSnKTe4SA8HAU"
         },
         {
            "name":"BTS",
            "href":"https://api.spotify.com/v1/artists/3Nrfpe0tUJi4K4DXYWgMUX",
            "id":"3Nrfpe0tUJi4K4DXYWgMUX",
            "type":"artist",
            "external_urls":{
               "spotify":"https://open.spotify.com/artist/3Nrfpe0tUJi4K4DXYWgMUX"
            },
            "uri":"spotify:artist:3Nrfpe0tUJi4K4DXYWgMUX"
         }
      ],
      "disc_number":"Decimal(""1"")",
      "href":"https://api.spotify.com/v1/tracks/3FeVmId7tL5YN8B7R3imoM",
      "track_number":"Decimal(""1"")",
      "external_urls":{
         "spotify":"https://open.spotify.com/track/3FeVmId7tL5YN8B7R3imoM"
      },
      "artist_id":"3Nrfpe0tUJi4K4DXYWgMUX",
      "preview_url":"https://p.scdn.co/mp3-preview/73bbc165dc2883cc59a0c8b46700af11eba03bc7?cid=74cbd487458843f1ad3f5fa1e914c02f",
      "is_local":false,
      "id":"3FeVmId7tL5YN8B7R3imoM",
      "explicit":false,
      "type":"track"
   }
]3
'''
0%