循环通过 peewee 结果在烧瓶中

loop through peewee results in flask

基于此回复:

cursor = db.execute_sql('select * from tweets;')
for row in cursor.fetchall():
    print row

cursor = db.execute_sql('select count(*) from tweets;')
res = cursor.fetchone()
print 'Total: ', res[0]

来自:Python Peewee execute_sql() example

如何把它带到flask app然后在网页中显示?

这是正确的吗:

model.py

def get_statistics():
        cursor = finDB.execute_sql('CALL Allstatistics;')
        for row in cursor.fetchall():
                return row

app.py

@app.route("/finance")
def finance():
        stats = model.get_statistics()
        return render_template('/finance.html', stats=stats)

但是如何在 table 中显示它?

问题在于您对以下内容的改编:

for row in cursor.fetchall():
    print row

这将逐一打印 return 由 fetchall() 编辑的所有行。

您试图将其改编成一个函数 returning 所有行:

def get_statistics():
    cursor = finDB.execute_sql('CALL Allstatistics;')
    for row in cursor.fetchall():
        return row

现在这将 return 只有第一行,因为 return 语句在第一次迭代时终止循环。

你真正想要的是这样的:

def get_statistics():
    cursor = finDB.execute_sql('CALL Allstatistics;')
    return cursor.fetchall()

这将正确 return 游标中的所有行,或者 None 如果没有结果行。

检查是否有非空结果,而不是 None return 一个空列表,你可以这样做:

def get_statistics():
    cursor = finDB.execute_sql('CALL Allstatistics;')
    rows = cursor.fetchall()
    if rows:
        return rows
    return []

关于 cursor.fetchone(),这将 return 光标的下一个可用行,或者 None 如果没有更多行可用。例如,您可以像这样遍历游标中的所有可用行:

rows = []
row = cursor.fetchone() # fetch first row, or None if empty result
while row is not None:
    rows.append(row)
    row = cursor.fetchone() # fetch the next row, if None loop terminates
return rows # return all collected results

对于您的用例,为您的结果构建一个更方便的数据结构可能会很有趣,例如list of dicts:

rows = []
row = cursor.fetchone()
while row is not None:
    rows.append({'foo': row[0], 'bar': row[1], 'baz': row[2]})
    row = cursor.fetchone()
return rows

请注意,这可以像这样类似地实现:

rows = []
for row in cursor.fetchall():
    rows.append({'foo': row[0], 'bar': row[1], 'baz': row[2]})
return rows

然后您可以在模板中编写,循环 for row in rows:

foo is {{row['foo']}} and bar is {{row['bar']}}

或者你可以构造一个 namedtuple 的列表,允许你在模板中编写:

foo is {{row.foo}} and bar is {{foo.bar}}