二手产品经理

二手产品经理

THIS IS RENO

spotify api -93 days- learn python online for 100 days

Record#

  1. Today's coding practice is a bit difficult, it involves retrieving data from Spotify.
  2. First, use a key to obtain a token, then use the token to retrieve data.
  3. After retrieving the data, reorganize it and play it on the webpage.
  4. Use different parameters with a request post to obtain the corresponding response data.

CODE#

main.py#

import requests, json, os
from requests.auth import HTTPBasicAuth
from flask import Flask, request

clientID = os.environ['client_id']
clientSecret = os.environ['client_scrent']

def searchmusic(artist):
  url = "https://accounts.spotify.com/api/token"
  data = {"grant_type":"client_credentials"}
  auth = HTTPBasicAuth(clientID, clientSecret)
  
  response = requests.post(url, data=data, auth=auth)
  accessToken = response.json()["access_token"]
  
  #artist = input("Artist: ").lower()
  artist = artist.replace(" ", "%20")
  
  url = "https://api.spotify.com/v1/search"
  headers = {'Authorization': f'Bearer {accessToken}'}
  search = f"?q=artist%3A{artist}&type=track&limit=5"
  
  fullURL = f"{url}{search}"
  #print(fullURL)
  musiclist=[]
  response = requests.get(fullURL, headers=headers)
  data = response.json()
  #print(json.dumps(data, indent=2))  
  for track in data["tracks"]["items"]:
    musiclist1 ={"name":track["name"],"url":track["preview_url"]}
    musiclist.append(musiclist1)
  return musiclist



app = Flask(__name__)
@app.route("/", methods=["GET"])
def index():
  f=open("index.html","r")
  page=f.read()
  f.close
  musiclist = "NONE"
  page = page.replace("{musiclist}",musiclist)
  return page


@app.route("/", methods=["POST"])
def search():
  f=open("index.html","r")
  page=f.read()
  f.close
  text=''
  year = request.form["year"]
  musiclist = searchmusic(year)
  #print(json.dumps(musiclist, indent=2))
  for music in musiclist:
    name = music["name"]
    url = music["url"]
    text1=f"""
    <h2>{name}</h2>
    <audio controls>
    <source src="{url}" type="audio/mpeg">
  </audio>
    """
    text += text1
    
  page = page.replace("{musiclist}",text)
  return page


app.run(host='0.0.0.0', port=81)

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.