added user class and working playlist fetching

This commit is contained in:
aj 2019-02-27 22:45:53 +00:00
parent 89acfa98ef
commit a194bcfd67
5 changed files with 73 additions and 25 deletions

13
main.py
View File

@ -1,6 +1,15 @@
import spotframework.net.auth as auth import spotframework.net.user as userclass
import spotframework.net.playlist as playlist
if __name__ == '__main__': if __name__ == '__main__':
print('hello world') print('hello world')
auth.refreshToken()
user = userclass.User()
user.refreshToken()
playlists = playlist.getPlaylists(user)
for playlist in playlists:
print(playlist['name'])
print(len(playlists))

View File

@ -1,23 +0,0 @@
import os
import requests
from base64 import b64encode
client_id = os.environ['SPOTCLIENT']
client_secret = os.environ['SPOTSECRET']
user_access_token = os.environ['SPOTACCESS']
user_refresh_token = os.environ['SPOTREFRESH']
#This sets up the https connection
#we need to base 64 encode it
#and then decode it to acsii as python 3 stores it as a byte string
def refreshToken():
idsecret = b64encode(bytes(client_id + ':' + client_secret, "utf-8")).decode("ascii")
headers = { 'Authorization' : 'Basic %s' % idsecret }
data = {"grant_type": "refresh_token", "refresh_token": user_refresh_token}
req = requests.post('https://accounts.spotify.com/api/token', data = data, headers = headers )
if req.status_code == 200:
user_access_token = req.json()['access_token']

View File

@ -0,0 +1,3 @@
api_url = 'https://api.spotify.com/v1/'

View File

@ -0,0 +1,33 @@
import requests
from . import const
limit = 50
def getPlaylists(user, offset = 0):
headers = {'Authorization': 'Bearer ' + user.access_token}
playlists = []
params = {'offset': offset, 'limit': limit}
req = requests.get(const.api_url + 'me/playlists', params = params, headers = headers)
print(req.text)
if req.status_code == 200:
print(req.text)
resp = req.json()
playlists = playlists + resp['items']
if resp['next']:
playlists += getPlaylists(user, offset + limit)
print(req.text)
return playlists
else:
return None

26
spotframework/net/user.py Normal file
View File

@ -0,0 +1,26 @@
import os
import requests
from base64 import b64encode
client_id = os.environ['SPOTCLIENT']
client_secret = os.environ['SPOTSECRET']
class User:
def __init__(self):
self.access_token = os.environ['SPOTACCESS']
self.refresh_token = os.environ['SPOTREFRESH']
def refreshToken(self):
idsecret = b64encode(bytes(client_id + ':' + client_secret, "utf-8")).decode("ascii")
headers = { 'Authorization' : 'Basic %s' % idsecret }
data = {"grant_type": "refresh_token", "refresh_token": self.refresh_token}
req = requests.post('https://accounts.spotify.com/api/token', data = data, headers = headers )
print(req.status_code)
print(req.text)
self.access_token = req.json()['access_token']