Skip to content

Instantly share code, notes, and snippets.

@chribsen
Created June 1, 2016 21:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chribsen/f7b520f5f74f359e81399634b5d1d7eb to your computer and use it in GitHub Desktop.
Save chribsen/f7b520f5f74f359e81399634b5d1d7eb to your computer and use it in GitHub Desktop.
Script retrieves genres based on PostgreSQL database called artist_name, that contains artist names
import psycopg2
import requests
import time
conn_dtu = psycopg2.connect("<connection_string>")
cur_dtu = conn_dtu.cursor()
cur_dtu.execute("select artist_name from data_lineup where spotify_id is null")
search_url = 'https://api.spotify.com/v1/search'
params = {'q':None, 'type': 'artist'}
for each in cur_dtu.fetchall():
params['q'] = each[0]
r = requests.get(search_url, params=params)
try:
artists = r.json()['artists']['items']
except KeyError:
print('ERROR ON ARTIST: ' + each[0])
continue
for each_artist in artists:
id = each_artist['id']
name = each_artist['name']
if len(each_artist['genres']) > 0:
genres = each_artist['genres'][0]
else:
genres = None
popularity = each_artist['popularity']
follower_count = each_artist['followers']['total']
if name.lower() == each[0].lower():
print('Found')
cur_dtu.execute("""update rf_lineup set
spotify_genre=%s,
spotify_followers=%s,
spotify_popularity=%s,
spotify_id=%s,
spotify_name=%s
WHERE artist_name=%s""",
(genres,
follower_count,
popularity,
id,
name,
each[0],))
break
conn_dtu.commit()
time.sleep(0.5)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment