簡體   English   中英

Python Flask 應用程序中的 for 循環僅重復 html 中的最后一個結果

[英]For loop in Python Flask application is only repeating the last result in html

我正在制作一個網絡表單,允許用戶選擇流派和年份,它將列出 API 中該流派和年份的所有歌曲(我知道很多歌曲,計划稍后添加更多字段以過濾掉它) . I tried this with just python and printing my values and it worked fine but doesn't display what i want in HTML.i have a for loop in my python code and in my HTML. 我對 Flask 不是很有經驗,有人可以幫忙嗎?

這是我的 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()

這是我的 HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Search</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
    <div class="container">
        <div>
            <h2 class="text-center">MUSIC SEARCH</h2> <br>
        </div>
                    
        <div class="form-group"> 
            <form action="" method="post">
            
                <p>
                    <label for="genre">Genre</label>
                    <input type="text" class="form-control" name="genre">
                </p>
                <p>
                    <label for="year">Year</label>
                    <input type="date" class="form-control" name="year" placeholder="Year">
                </p>
                <p>
                    <input type="submit" class="btn btn-secondary btn-lg btn-block" >
                </p>
            </form>
        </div>
    </div>
    
    <div class="container">
        {% for result in results %}
            <div class="p-3 mb-2 bg-info text-white">
                <p>{{song}}</p>
            </div>
        {% endfor %}
    </div>
    
</body>
</html>

我可以在 python 腳本中的 For 循環中打印所有結果,但我無法在 html 中獲得 output。 它只是重復最后一個結果。如果我 output 結果我滿了,我會得到不同的結果

據我所見,在您的模板代碼中,您正在迭代結果,因此為了顯示歌曲,您應該在模板代碼中使用如下內容:

{% for result in results %}
        <div class="p-3 mb-2 bg-info text-white">
            <p>{{result['song']}}</p>
        </div>
    {% endfor %}

或者在您的 flask 代碼中創建一個包含歌曲的列表,將其發送到模板並像這樣迭代它:

songs = []
for result in results:
    songs.append(result['song'])
    
return render_template('index.html', songs=songs)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM