Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/76.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Flask应用程序中的For循环仅在html中重复最后一个结果_Python_Html_Api_Flask - Fatal编程技术网

Python Flask应用程序中的For循环仅在html中重复最后一个结果

Python Flask应用程序中的For循环仅在html中重复最后一个结果,python,html,api,flask,Python,Html,Api,Flask,我正在制作一个网络表单,让用户选择一个流派和一年,它将从API中列出该流派和一年中的所有歌曲(我知道很多歌曲,计划稍后添加更多字段以过滤)。我只是用python和打印我的值来尝试这个方法,效果很好,但没有在HTML中显示我想要的内容。我在烧瓶方面不是很有经验,有人能帮忙吗 这是我的python代码中还有for循环的部分: from flask import Flask, render_template, request import requests from jinja2 import Tem

我正在制作一个网络表单,让用户选择一个流派和一年,它将从API中列出该流派和一年中的所有歌曲(我知道很多歌曲,计划稍后添加更多字段以过滤)。我只是用python和打印我的值来尝试这个方法,效果很好,但没有在HTML中显示我想要的内容。我在烧瓶方面不是很有经验,有人能帮忙吗

这是我的python代码中还有for循环的部分:

from flask import Flask, render_template, request
import requests
from jinja2 import Template
import json

def song_search(genre, year):
    app_id = ''
    app_key = ''
    result = requests.get('https://<api_address>/search?q={}&app_id={}&app_key={}&calories<={}'.format(genre, app_id, app_key, year))
    data = result.json()
    return data['hits']

DEBUG = True
app = Flask(__name__)
app.config.from_object(__name__)
app.config['SECRET_KEY'] = ''

@app.route('/', methods=['post', 'get'])
def run():
    if request.method == 'POST':
        genre = request.form.get('genre')  # access the data inside 
        year = request.form.get('year')
        results = song_search(genre, year)
        for result in results:
            song = result['song']
        
        return render_template('index.html', results=results)
    

if __name__ == "__main__":
    app.run()
从烧瓶导入烧瓶,呈现模板,请求
导入请求
从jinja2导入模板
导入json
def song_搜索(流派,年份):
应用程序id=“”
应用程序_键=“”

结果=请求。获取('https:///search?q={}&app_id={}&app_key={}&carries据我所见,在模板代码中,您正在迭代结果,因此为了显示歌曲,您应该在模板代码中使用以下内容:

{% for result in results %}
        <div class="p-3 mb-2 bg-info text-white">
            <p>{{result['song']}}</p>
        </div>
    {% endfor %}
songs = []
for result in results:
    songs.append(result['song'])
    
return render_template('index.html', songs=songs)
songs = []
for result in results:
    songs.append(result['song'])
    
return render_template('index.html', songs=songs)