Python API调用,输出到Flask forloop

时间:2019-10-02 20:20:41

标签: javascript python jquery flask

我正在使用flask编写网络python东西,基本上是通过for循环中的flask模板将数据库中的所有记录显示为列表。

现在,我想调用Spotify API,并在每个播放列表旁边显示Spotify API的封面图像,但是我不知道如何匹配ID并在for循环中进行调用

我可以从Flask进行API调用,还是可以在该循环内通过调用来调用函数? 我也尝试过使用jQuery AJAX调用,但是显示的图像对于数据库中最后一个项目的所有项目都是相同的

import os
import requests
import json
from dotenv import load_dotenv
from datetime import datetime
##loading credenditls from seperate file
from credentials import auth_data, auth_string
from flask import Flask, redirect, render_template, request, session, url_for
from flask_pymongo import PyMongo
from bson.objectid import ObjectId
#enviorement virables loading
load_dotenv()
DBNAME = os.getenv("DBNAME")
DATABASEURI = os.getenv("URI")
#calling api for spotify token
token_response = requests.post('https://accounts.spotify.com/api/token',
                    data = auth_data,
                    headers = auth_string,)  
token_response_data = token_response.json()
##token
the_token = token_response_data['access_token']

app = Flask(__name__)

#Connecting to database
app.config["MONGO_DBNANE"] = DBNAME
app.config["MONGO_URI"] = DATABASEURI

mongo = PyMongo(app)

def get_playlist_image(id):
    image_response = requests.get('https://api.spotify.com/v1/playlists/' + id + '/images',
                           headers={'Authorization':'Bearer '+ the_token})
    image_response_data = image_response.json()
    image_url = image_response_data[0]['url']
    return image_url

@app.route('/')
@app.route('/home')
def display():
    the_playlists = mongo.db.playlists.find()
    for list in the_playlists:
        spotifyid = list['spotify_id']
        the_image_url = get_playlist_image(spotifyid)
    return render_template("home.html", playlists=mongo.db.playlists.find(), image_url=the_image_url, spotifyid = list['spotify_id']
    )

1 个答案:

答案 0 :(得分:0)

好吧,我必须有点笨,我找到了一种方法。 您可以在烧瓶模板中调用带有变量的函数

Python函数:

    @app.route('/')
@app.route('/home')
def display():
    def get_playlist_image(id):
        image_response = requests.get('https://api.spotify.com/v1/playlists/' + id + '/images',
                           headers={'Authorization':'Bearer '+ the_token})
        image_response_data = image_response.json()
        image_url = image_response_data[0]['url']
        return image_url
    return render_template("home.html", playlists=mongo.db.playlists.find(), get_playlist_image=get_playlist_image)

HTML模板:

 <div id="api">
                    <img src="{{get_playlist_image(p.spotify_id)}}"/>
                </div>