【问题标题】:loop through peewee results in flask循环通过peewee导致烧瓶
【发布时间】:2018-06-15 04:46:24
【问题描述】:

基于此回复:

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,然后显示在网页中?

这对吗:

模型.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)

但是如何在表格中显示呢?

【问题讨论】:

  • 您想在 html 表格中显示它们吗?请显示统计信息的样子? stats 是针对什么数据类型的??一个列表?字典?
  • 在 HTML 中是的,当我直接在 mysql 中运行此存储过程时,我得到 6 列和 22 行:文本 | -55585.73 | -24834.28 | -2069.94 | -895.19 |空
  • 结果的数据结构是什么?
  • 我不知道...列表?
  • 我显然不是...在我的 peewee 模型中:def get_tags(self): return tag_list.select(),从表中给我输出,然后在 flask app.py 中我只是这样做output = model.get_tags() 然后在应用程序路由中:@app.route(.... output=output...),然后在网页上我可以使用列标题
  • 但这些都不适用于 db.execute_sql() 方法。
    {{ row.header } 循环}

标签: python flask peewee


【解决方案1】:

问题在于您对以下内容的适应:

for row in cursor.fetchall():
    print row

这将一一打印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()

这将正确返回游标中的所有行,如果没有结果行,则返回None

通过检查是否有非空结果,而不是 None 返回一个空列表,您可以这样做:

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

关于cursor.fetchone(),这将返回光标的下一个可用行,如果没有更多行可用,则返回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}}

【讨论】:

  • 第一个选项适用于 {{ row[0] }}。第二个选项使应用程序崩溃并突出显示 rows=cursor.fetchall(): 的语法错误。没有一个选项适用于 {{row.ColumnHeader}}
  • @michal 第二个选项有一个额外的: 来自之前的编辑,对此感到抱歉。这些都不适用于{{row.ColumnHeader}},因为每个row 的类型都是list,并且不会将字段作为由列标题命名的属性。
  • 我的错误,拼写错误,在 fetchall() 之后添加了 ':',这两个选项都可以正常工作,谢谢!
  • 你能更进一步解释一下 fetchone() 吗? def get_stats_summary(): cursor = finDB.execute_sql('call AllStatisticsSum()') return cursor.fetchone() 然后尝试循环没有任何东西显示
  • @michal 查看编辑,您可以使用fetchone() 从光标中获取单行。
猜你喜欢
  • 2020-05-25
  • 1970-01-01
  • 2021-10-27
  • 2022-01-01
  • 1970-01-01
  • 2012-07-23
  • 1970-01-01
  • 2014-11-25
  • 1970-01-01
相关资源
最近更新 更多