IndexError: list index out of range python (flask)

IndexError: list index out of range python (flask)

我正在制作 python 应用程序,我想知道为什么我的程序显示 IndexError: list index out of range。我想创建显示来自数据库的数据的烧瓶应用程序。

烧瓶:

@app.route('/', methods=['POST','GET'])
def displaytask():
    mycursor = mydb.cursor()
    mycursor.execute("SELECT * FROM tasks")
    data = mycursor.fetchall()
    empty_table=false
    if data[0][0]==0:
          empty_table=true
    return render_template('index.html', data=data, value=empty_table)

仅当数据已插入时才显示数据,如果数据库为空则显示错误消息。

错误信息:if data[0][0]==0: IndexError: list index out of range

我想在 jinja 块中显示数据:

   {% for row in data %}
        {% if value == true %}
           <li><span class='text'>No Record Found.</span></li>
        {% endif %}
        <li><span class="text">{{ row[1] }}</span>
         <i id="removeBtn" class="icon fa fa-trash"></i>
        </li>
   {% endfor %}

如果数据库中没有数据,那么 data 将为空列表。 如果您然后尝试访问它 data[0][0] 那么您将收到超出范围的错误,因为空列表中没有位置 0

In [420]: r = []
In [421]: r[0]
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
<ipython-input-421-8418cdc095ae> in <module>
----> 1 r[0]

IndexError: list index out of range

您需要在尝试访问之前检查数据是否为空。

如果您只想检查数据是否为空,只需将数据变量传递给模板,然后使用 jinja 检查。所以神社模板是这样的:

{% if data %}
{% for row in data %}
<li>
    <span class="text">{{ row[1] }}</span>
    <i id="removeBtn" class="icon fa fa-trash"></i>
</li>
{% endfor %}
{% else %}
<li><span class='text'>No Record Found.</span></li>
{% endif %}

更多测试在:https://jinja2docs.readthedocs.io/en/stable/templates.html#list-of-builtin-tests