我正在后端使用 Flask 構建自定義 Spotify 音樂播放器來處理對 Spotify API 的呼叫。它從當前播放的曲目中獲取資訊并填充本地網頁。我現在需要輪詢 Spotify API(每 2 秒左右)以檢查歌曲是否已更改,如果已更改,請更新網頁(希望使用 JavaScript,因此無需重繪 頁面)。我不確定如何用 Flask 做到這一點,或者是否有更好的方法來解決這個問題。我相信我可以通過創建和呼叫異步函式來進行輪詢來解決這個問題,但是如果發現了更改,我不確定從哪里開始。
這是我迄今為止的 Spotify 視圖。我在 spotify.py 檔案中的自定義 auth 和 now_playing 函式中使用了 spotipy 庫。
@app.route('/spotify')
def spotify():
# Get Spotify instance and authorization token
authData = dev.auth()
sp = authData[0]
token = authData[1]
current = dev.now_playing(sp, token)
# Assign individual track information to variable for sending to web page via Jinja
separator = ', '
return render_template('spotify.html',
artists = separator.join(current[0]),
song = current[1],
album = current[2],
cover_url = current[3],
year = current[4],
auth_tok = token
)
我的 Web 開發經驗有限,這是我第一次使用 Flask。我正在使用這個專案來了解更多資訊,但遇到了這個障礙。
uj5u.com熱心網友回復:
概念
輪詢 API 的一個好方法是在 javascript 中安排請求,然后等待一定時間(不超過 10-30 秒)讓服務器保留請求以查看歌曲是否更改,然后回傳結果。如果發現結果早于 10-30 秒,則服務器提前回傳。客戶端看到請求正在進行中,并且可以在服務器擁有的整個視窗中接收它,只要請求沒有超時(超過 30 秒左右)。您也可以每隔幾秒鐘簡單地請求 url 進行檢查,但這會占用大量系統資源。
介面代碼
from flask import Flask, redirect
song = "" # global identifier
@app.route("/track", methods=["GET"])
def track():
for _ in range(10):
time.sleep(1)
global song # regrab the song value every iteration
current = dev.now_playing(sp, token) # get current song
if current[1] != song: # song changed
song = current[1]
return redirect("http://www.website.com/spotify", code=302) #essentially an automatic refresh by redirecting to itself, and will regrab the song data!
return {}, 200 # give the client SOMETHING so the request doesn't timeout and error
@app.route('/spotify')
def spotify():
global song
# Get Spotify instance and authorization token
authData = dev.auth()
sp = authData[0]
token = authData[1]
current = dev.now_playing(sp, token)
# Assign individual track information to variable for sending to web page via Jinja
separator = ', '
song = "" # assign the song value to whatever is sent to the client
return render_template('spotify.html',
artists = separator.join(current[0]),
song = current[1],
album = current[2],
cover_url = current[3],
year = current[4],
auth_tok = token
)
提供的代碼將接受來自客戶端的請求,然后檢查global song客戶端上次重繪 頁面時代表歌曲的值是否與 API 使用的當前歌曲不同。在這種情況下,服務器將發送一個重定向代碼,因此客戶端將重定向并基本上重繪 它所在的當前頁面,從而獲取歌曲和資訊!
Javascript
javascript 代碼將使用簡單的請求,并使用 GET 不斷獲取端點 /track 上的服務器資料。它可以在這里找到,也可以通過自己研究 javascript get requests來找到。要連續執行請求,請使用以下代碼。
function stopFunction(){
clearInterval(myVar); // stop the timer
}
$(document).ready(function(){
myVar = setInterval("makeRequest()", 1000);
});
這不是我提供的一段可擴展的代碼,但應該適用于私有訪問,并且可以在概念上適應可擴展的端點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/386092.html
標籤:javascript Python 烧瓶 异步 发现
