Flask。如何在Flask中使用外部模块并将数据传递到html?

2024-05-16 13:31:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在构建桌面应用程序UI,并尝试将所有内容移动到Flask中,以便可以在html/css/boostrap中显示所有内容。你知道吗

但是下面的代码不起作用。你知道吗

如何让found.productId和其他循环显示在ali.html上?你知道吗

应用程序类型

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 %}

Tags: 应用程序内容htmlproductalitdaliexpressfound
1条回答
网友
1楼 · 发布于 2024-05-16 13:31:27

第一个问题是print()返回None。所以:

founds = print(productId, productTitle, salePrice, originalPrice, imageUrl)

只是等价于founds = None。基本上没用。你知道吗

所以,首先要做的是给founds一个结构。您的选项基本上是dictlist。在您的示例中使用列表是最简单的(但不一定是您的实际代码):

应用程序类型

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非常相似。你知道吗

相关问题 更多 >