From 85f27b081ca6e1ea5b626346848c5bc4ae5ea9ee Mon Sep 17 00:00:00 2001 From: Jef Roosens Date: Wed, 19 May 2021 12:35:34 +0200 Subject: [PATCH] Added temporary first Spotify implementation --- app/spotify.py | 55 +++++++++++++++++++++++++++++++++++++++++++ tests/test_succeed.py | 3 --- 2 files changed, 55 insertions(+), 3 deletions(-) create mode 100644 app/spotify.py delete mode 100644 tests/test_succeed.py diff --git a/app/spotify.py b/app/spotify.py new file mode 100644 index 0000000..a484646 --- /dev/null +++ b/app/spotify.py @@ -0,0 +1,55 @@ +import base64 +import requests + + +class CredentialError(Exception): + pass + + +class Spotify: + def __init__(self, client_id, client_secret): + self.client_id = client_id + self.client_secret = client_secret + self.access_token = "" + self.token_type = "" + self.expiration_time = 0 + self.scope = "" + + def request_token(self): + b64_encoded = base64.b64encode( + "{}:{}".format(self.client_id, self.client_secret).encode() + ) + headers = {"Authorization": "Basic {}".format(b64_encoded.decode("ascii"))} + + data = {"grant_type": "client_credentials"} + + post = requests.post( + "https://accounts.spotify.com/api/token", headers=headers, data=data + ) + status_code = post.status_code + + if status_code == 401: + raise CredentialError("Provided credentials are not correct.") + + if status_code == 200: + self.access_token = post.json()["access_token"] + self.token_type = post.json()["token_type"] + self.expiration_time = post.json()["expires_in"] + self.scope = post.json()["scope"] + + def search(self, search_term, types): + if not self.access_token: + self.request_token() + + encoded_search_term = urllib.parse.quote(search_term) + full_url = "https://api.spotify.com/v1/search?q={}&type={}".format( + encoded_search_term, ",".join(types) + ) + + get = requests.get( + full_url, headers={"Authorization": "Bearer " + self.access_token} + ) + + results = get.json() + + return results diff --git a/tests/test_succeed.py b/tests/test_succeed.py deleted file mode 100644 index 81db0b6..0000000 --- a/tests/test_succeed.py +++ /dev/null @@ -1,3 +0,0 @@ -def test_succeed(): - """Placeholder test to make CI succeed.""" - pass