【问题标题】:How to display multiple images from an API in Flask如何在 Flask 中显示来自 API 的多个图像
【发布时间】:2019-05-03 02:07:40
【问题描述】:

我正在使用 Fortnite API,更具体地说是 Python package,来编写一个 Flask Web 服务器。我想检索商店图像并将它们显示在我的烧瓶网络服务器上。请注意,我对 Python 和 Flask 还很陌生。

我尝试使用@app.route("/shop") 并创建一个for 循环来获取图片,然后返回return item.information,这应该会为我提供图片的所有链接(链接看起来像this)并打印它们。我想将它们显示为图像。

这是我尝试过的,我知道它不会将它们显示为图像,但我真的很新。奇怪的是,它甚至没有返回所有的链接。

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

我希望输出显示商店中每件商品的图像,但它只打印一个链接而没有图像。

【问题讨论】:

  • 你只能在函数中使用一次return - 这就是return 在所有函数和所有语言中的工作方式——所以你只能使用return items。或者使用模板,然后您可以在模板中使用for循环从每个项目中获取information。或者创建包含信息的列表并返回此列表。

标签: python api flask


【解决方案1】:

函数只能执行一次return

这样你就可以退货了

items = shop.get_items()
return items

或者您可以使用information 创建新列表并返回此列表

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

要显示为图像,您必须使用 HTML 模板和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)

'all_images.html'

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

或使用items

from flask import Flask, render_template

items = shop.get_items()

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

'all_images.html'

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

编辑:它并不流行,但你也可以直接在函数中生成 HTML

items = shop.get_items()

html = ''

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

return html

【讨论】:

  • 我在使用倒数第二个“items”方法时出现内部服务器错误。 @furas
  • 尝试其他方法。
  • 对不起,我做错了。现在我收到以下错误:
  • 最后一行:jinja2.exceptions.TemplateNotFound: all_images.html - 你必须创建文件all_images.html,它必须在子文件夹templates - 文档:Rendering Templates
  • 我成功了!谢谢@furas。标记为正确答案。
猜你喜欢
  • 2015-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多