웹개발/프로젝트#1-MasterPiece

[프로젝트#1-MasterPiece] Spotify API 추가하기

2soon2soon 2024. 5. 12. 03:16

현재 MasterPiece는 사용자가 직접 노래를 등록해야하는 번거로움이 있다.

이를 해소하기 위해 Spotify의 노래 데이터베이스를 API로 가져와 MasterPiece의 데이터베이스에 저장하겠다.

 

사실 MasterPiece는 국내 음반 후기 및 평점사이트이기 때문에 Spotify보다는 멜론, 벅스, 지니 등의 국내 스트리밍 서비스의 API를 가져오는 것이 적합한데 이들은 API를 제공하지 않아 불가피하게 Spotify를 선택하게 되었다. 따라서 국내음악임에도 불구하고 영어로 출력되는 노래들이 꽤 존재한다는 단점이 있다. 

어찌됐든, Spotify의 API를 가져오도록 하자. 

 

[Spotify API 가져오는 방법]

1. Spotify Developers 사이트에 접속

2. Dashboard에서 Create App

3. App name, description, Redirect Urls(호스팅할 주소) 등의 정보를 입력하고 Client ID와 Client secret를 발급받는다.

   ㄴ 발급받은 id와 secret을 통해 flask에서 spotify의 데이터베이스에 접근한다고 생각하면 될 듯하다.

4. spotify의 데이터베이스에 접근하고 싶은 파일에 다음과 같은 코드를 추가한다.

import spotipy
from spotipy.oauth2 import SpotifyClientCredentials
import pprint
 
cid = '1c2246a49faf498eb3134fffsd67ddf912f'
secret = 'asdjakdfadjvcb2312afdasd'
client_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)
 
sp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)

  cid와 secret에는 앞서 3에서 발급받은 id와 secret을 기입한다.

  놀랍게도 Spotify에서 파이썬에 자체 라이브러리 Spotipy를 제공한다.

  spotipy를 import하고 spotify객체를 생성하면 그 객체를 통해 다양한 속성에 접근 가능하다.

 

[Spotipy로 MasterPiece에서 Spotify의 노래 검색하고 출력하기]

@bp.route('/')
def _list():
    page = request.args.get('page', type=int, default=1)  # 페이지
    kw = request.args.get('kw', type=str, default='') # 검색어
    song_list = Song.query.order_by(Song.write_date.desc())
    song_list = song_list.paginate(page=page, per_page=5)
    if kw:
        search = sp.search(q=kw, limit=10, type="track", market='KR')
        return render_template("song_list.html", song_list=song_list, search=search)
    else:
        return render_template("song_list.html", song_list=song_list)

html에서 Get방식으로 _list를 호출하면서 kw(검색어)를 넘기고, kw를 spotify객체 sp의 sp.search를 통해 검색한다.

검색의 결과 search를 다시 html로 넘겨주면 검색결과가 화면에 출력된다.

 

 

 

이 과정에서 모델도 수정하고 기타 기능들도 Spotipy에 맞게 수정하였다.

 

<구현한 것>

노래 스포티파이에 검색해서 화면에 출력하는 기능 구현 완료
Song 모델에 spotify의 노래 id 어트리븉 추가 완료
노래 검색했을 때 db에 등록돼있는 노래면 평균평점 출력, db에 등록돼있지 않은 노래면 평균평점 None으로 출력하는 기능 구현 완료

<구현해야 할 것>
노래제목 링크를 클릭했을 때
db에 등록돼있는 노래면 추가로 후기/평점 작성 가능하게끔,
db에 등록돼있지 않은 노래면 노래를 db에 등록한 뒤 후기평점 작성 가능하게끔 만들기

 

 

Les goooo!