So, I'm messing around with the star wars swapi API, and rendering my api search onto an html file as a string, however I cannot seem to separate the titles in the string by line:
from flask import Flask, render_template, request, redirect
import requests
import json
import swapi
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def index():
url = "https://swapi.co/api/"
star_wars_api = requests.get(url)
result = ''
if request.method == 'POST':
films = requests.get(star_wars_api.json()['films'])
if films.status_code == 200:
if request.form['search'] == "films":
film_json = films.json()
for film in film_json['results']:
result += str(film['title'])
return render_template('index.html', results=result)
else:
return render_template('index.html')
if __name__ == "__main__":
app.run(debug=True)
Here is the HTML file:
{% extends 'base.html'%}
{% block head %} {% endblock %}
{% block body %}
<form action="/" method="POST">
<label for="search">Search:</label>
<input class="form-control" type="text" name="search" id="search" placeholder="Search" aria-label="Search">
<br>
<input type="submit" value="Post">
</form>
<p> {{ results }}</p>
{% endblock %}
Here is the output: (on the index.html page)
"A New HopeAttack of the ClonesThe Phantom MenaceRevenge of the SithReturn of the JediThe Empire Strikes BackThe Force Awakens" (without the quotes)
results? If single line then you can't split it. If you have many lines then replace'\nwith<br>, or use<pre></pre>instead of<p></p>{% for %}in template to display eveery title in separate<p>or add<br>to every title.