python - 烧瓶-Python。如何在 Flask 中使用外部模块并将数据传递给 html?
问题描述
我正在构建桌面应用程序 UI,我正在尝试将所有内容都移到 Flask 中,这样我就可以在html/css/boostrap
.
但是下面的代码不起作用。
你如何得到found.productId
和其余循环显示ali.html
?
应用程序.py
from aliexpress_api_client import AliExpress
@app.route('/ali')
def ali():
aliexpress = AliExpress('1234', 'bazaarmaya')
data = aliexpress.get_product_list(['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl'],
keywords="shoes", pageSize='40')
for product in data['products']:
productId = product['productId']
productTitle = product['productTitle']
salePrice = product['salePrice']
originalPrice = product['originalPrice']
imageUrl = product['imageUrl']
founds = print(productId, productTitle, salePrice, originalPrice, imageUrl)
if founds == founds:
return render_template('ali.html', founds=founds)
return render_template('ali.html')
阿里.html
{% extends 'layout.html' %}
{% block body %}
<table>
<tr>
{% for found in founds %}
<td>{{found.productId}}</td>
<td>{{found.productTitle}}</td>
<td>{{found.salePrice}}</td>
<td>{{found.originalPrice}}</td>
<td>{{found.imageUrl}}</td>
{% endfor %}
</tr>
</table>
{% endblock %}
解决方案
第一个问题是,print()
将返回 None
。所以:
founds = print(productId, productTitle, salePrice, originalPrice, imageUrl)
仅相当于founds = None
。基本没用。
所以,首先要做的是给出founds
一个结构。您的选择基本上是 adict
和 a list
。在您的示例中使用列表最简单(但不一定是您的实际代码):
应用程序.py
from aliexpress_api_client import AliExpress
@app.route('/ali')
def ali():
aliexpress = AliExpress('1234', 'bazaarmaya')
data = aliexpress.get_product_list(['productId', 'productTitle', 'salePrice', 'originalPrice', 'imageUrl'],
keywords="shoes", pageSize='40')
for product in data['products']:
productId = product['productId']
productTitle = product['productTitle']
salePrice = product['salePrice']
originalPrice = product['originalPrice']
imageUrl = product['imageUrl']
founds = [productId, productTitle, salePrice, originalPrice, imageUrl]
return render_template('ali.html', founds=founds)
注意:无论哪种方式都有问题。循环将覆盖每个循环上的for
数据,所以也许你想要一个字典,但你需要给它唯一的键。或者您预先定义一个列表并在循环中附加到它。这个例子只会给你循环中的最后一个项目,你可以相应地处理它。
然后:
阿里.html
{% extends 'layout.html' %}
{% block body %}
<table>
<tr>
{% for found in founds %}
<td>{{found}}</td>
<td>{{found}}</td>
<td>{{found}}</td>
<td>{{found}}</td>
<td>{{foundl}}</td>
{% endfor %}
</tr>
</table>
{% endblock %}
.
如果您将字典传递给模板并希望通过键访问内容,则可以使用该表示法。但是还有其他问题需要首先解决,因此这个答案可能会陷入太深的风险。jinja2
语法(在你的模板中)非常像普通的 python。
推荐阅读
- mongodb - 使用带有 updateOne() 方法的 upsert 来执行更新操作
- java - 我如何在 smallrye 兵变中对 Multi 进行排序
- javascript - 如何在 discord.js 上停止 setInterval 函数?
- r - 如何使用 ifelse 条件语句在 R 中绘制列的选定数据
- android - 在 Flutter 中添加 Firebase.initializeApp() 的正确位置在哪里?
- glib - 为什么我的 GLib 超时有时没有被破坏?
- javascript - 查找容器内 div 的索引
- machine-learning - 在奇点中绑定可写目录
- serenity-platform - LinkingSetRelation 中的错误 - 无效转换 ... 作为对象
- javascript - Sequelize - 从具有 hasMany 关系的现有实例创建新的关系记录