首页 > 解决方案 > 烧瓶-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 %}

标签: pythonflask

解决方案


第一个问题是,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。


推荐阅读