二手产品经理

二手产品经理

THIS IS RENO

spotify api -93天- 在线学python100天

记录#

  1. 今天的编码练习有点难,是从 spotify 获取数据。
  2. 先使用 key 获取 token,再使用 token 获取数据。
  3. 获取后的数据再进行重组,在页面中进行播放。
  4. 使用 request post 不同的参数,获取相应的返回数据。

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(arist):
  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"]
  
  #arist = input("Artist: ").lower()
  arist = arist.replace(" ", "%20")
  
  url = "https://api.spotify.com/v1/search"
  headers = {'Authorization': f'Bearer {accessToken}'}
  search = f"?q=artist%3A{arist}&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)

加载中...
此文章数据所有权由区块链加密技术和智能合约保障仅归创作者所有。