I am making a webform which lets the user choose a genre and a year and it will list all the songs from that genre and year from an API (it's a lot of songs i know, planning to add more fields later to filter it down). 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. I'm not very experienced in Flask, can someone help?
This is my the part of my python code that also has the for loop:
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()
This is my 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>
I can print all the results in the For loop in a python script but i can't get the output in html. It just repeats the last result.If i output results i full I get different results