Braythor Codes
Braythor Codes

Reputation: 33

How to display multiple images from an API in Flask

I'm using Fortnite API, more specifically the Python package, to write a Flask web server. I want to retrieve the Shop images and display them on my flask web server. Please note that I am fairly new to Python and Flask.

I've tried using @app.route("/shop") and making a for loop to get the pictures, and returning return item.information which should give me all of the links to the image (links look like this) and print them. I want to display them as images.

Here's what I've tried, I know it doesn't show them as images but I'm really new. The weird thing is, it doesn't even return all of the links.

from flask import Flask
from FortniteAPI import Shop

app = Flask(__name__)

@app.route("/shop")
def shop():
    shop = Shop()
    items = shop.get_items()
    for item in items:
        return item.information

I expected the output to show images of each item in the shop, yet it only prints one link and no images.

Upvotes: 1

Views: 4208

Answers (1)

furas
furas

Reputation: 142641

Functions can execute return only once.

So you can return items

items = shop.get_items()
return items

Or you can create new list with information and return this list

items = shop.get_items()
info = [x.information for x in items]
return info

To display as images you have to use HTML template and render_template()

from flask import Flask, render_template

items = shop.get_items()
info = [x.information for x in items]

return render_template('all_images.html', links=info)

And in 'all_images.html'

{% for url in links %}
<img src="{{ url }}"/>
{% endfor %}

Or using items

from flask import Flask, render_template

items = shop.get_items()

return render_template('all_images.html', links=items)

And in 'all_images.html'

{% for url in links %}
<img src="{{ url.information }}"/>
{% endfor %}

EDIT: it is not popular but you can also generate HTML directly in function

items = shop.get_items()

html = ''

for x in items:
    html += '<img src="{}"/>'.format(x.information)

return html

Upvotes: 2

Related Questions