二手产品经理

二手产品经理

THIS IS RENO

spotify api -93天- 在线学python100天 音樂串流API -93天- 在線學習Python100天

#記錄

  1. 今天的編碼練習有點難,是從 spotify 獲取數據。
  2. 先使用 key 獲取 token,再使用 token 獲取數據。
  3. 獲取後的數據再進行重組,在頁面中進行播放。
  4. 使用 request post 不同的參數,獲取相應的返回數據。
    #代碼

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)

載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。