batch 형식으로 데이터 가져오기 - helloMinji/chatbot_spotify GitHub Wiki
batch로 데이터 가져오기
파일로 데이터 가져오기는 single item hit : artist 하나씩 url의 parameter에 넣어서 하나씩 requests 실행
→ batch 형식에서는 artist 여러개를 묶어서 requests 실행 (모든 api가 이 기능을 제공하는 것은 아니다)
현재까지 DB(artists 테이블)에 있는 id값을 모두 불러온다
cursor.execute("SELECT id FROM artists")
artists = []
for (id, ) in cursor.fetchall():
artists.append(id)
50개씩 가져와서 리스트로 만든 것을 하나의 item으로 해서 artist_batch 리스트에 넣는다
artist_batch = [artists[i: i+50] for i in range(0, len(artists), 50)]
데이터 가져오기
for i in artist_batch:
ids = ','.join(i) # 리스트로 묶여있던 것을 string으로 만든다
# 요청을 위한 URL 생성
URL = "https://api.spotify.com/v1/artists/?ids={}".format(ids)
r = requests.get(URL, headers=headers)
raw = json.loads(r.text)
데이터 확인
- print(raw)
- print(len(raw['artists']))
가져온 데이터로 DB 업데이트
리스트 생성 : artist_batch 리스트 아래
artist_genres = []
리스트에 데이터 추가 : raw = json.loads 아래
for artist in raw['artists']: # API 결과에서 하나씩 불러오기
for genre in artist['genres']: # genre key값
artist_genres.append(
{
'artist_id': artist['id'],
'genre': genre
}
)
데이터 insert & update (내용을 까먹었다면)
for data in artist_genres:
insert_row(cursor, data, 'artist_genres')
conn.commit() # 변경사항 적용
cursor.close() # DB 연결 끊기