首页 > 解决方案 > 如何停止加载的变量在 Flask 中重复?

问题描述

我正在使用来自 ERP 的 API 端点构建一个简单的数据分析 Web 应用程序。

我想在表格中显示我的查询结果,所以我遍历结果并且我的数据得到了很好的显示。但是,当我刷新页面时,我的数据会重复。

我的问题和这篇文章一样。

我尝试使用上面帖子的解决方案修复我的代码,但没有成功。

这是我的 Flask 应用程序的路线

@app.route('/results', methods=["POST", "GET"])
def results():
    code = hasCode()
    if request.method == "POST":
        quote_reference = request.form["quote"]
        products = resultsList(code, quote_reference)

        try:
            return render_template("results.html", products=products)

        except BaseException:
            return "There was a problem with your request"

    else:
        return render_template("/")

我的产品在 resultList() 函数中启动,并引用下面的函数:

def resultsList(code, quote_reference):
    """Creates a list of results that can be passed to the template of the
    results.html template
    """
    # initiating the variable
    my_list = {
        'quantity': [],
        'description': [],
        'price': [],
        'img': []
    }

    # The pandalize function fetches the data from the ERP
    query = pandalize(code, quote_reference)

    # Grabbing all reasults from the "pandalize function" and appending them to the list
    for i, row in query.iterrows():
        my_list["quantity"].append(row["quantity"])
        my_list["description"].append(row["name"])
        my_list["price"].append(row["price"])
        my_list["img"].append(row["id"])

    # Zipping the list
    products = zip(
        my_list["quantity"],
        my_list["description"],
        my_list["price"],
        my_list["img"]
    )

    return products

最后,循环位于 results.html 文件中:

{% for i in products %}
      <tr>
        <td class="quantity">{{ i[0] }}</td>
        <td class="description">{{ i[1] }}</td>
        <td class="price">{{ i[2] }}</td>
        <td class="img">{{ i[3] }}</td>
      </tr>
{% endfor %}

根据这个答案,我需要在我的 resultsList() 函数中初始化我的列表(产品)才能工作。但是,我仍然遇到数据翻倍的情况。

我真的不明白我做错了什么。有任何想法吗 ?

标签: htmlpython-3.xvariablesflask

解决方案


检查所有函数的结果并返回上游后,似乎原来的答案是正确的。我每次都需要初始化列表。

我注意到我的初始列表是由我的请求填充的('pandalize()' 函数)。这样做的效果是,每次调用 pandalize 函数时,列表都会变得越来越长。

现在已经修复了。


推荐阅读