【问题标题】:Change the format of the returned data when selecting records. Flask [duplicate]选择记录时更改返回数据的格式。烧瓶[重复]
【发布时间】:2019-11-11 22:43:03
【问题描述】:

在我的烧瓶应用程序中,在 routes.py 中,我得到带有 Location 模型的特定字段的条目:

...
location = db.session.query(Location.id, Location.name,Location.code, Location.id_parent).all()
newLocat = list( location)
print(str(newLocat))
...

返回数据的格式如下:

[(1, 'Test1', 101, 0), (2, 'Test2', 202, 1)]

如何让返回的数据格式变成这样?

[{'id': '1', 'name': 'Test1','code':101, 'id_parent': '0'}, {'id': '2', 'name': 'Test2','code':202, 'id_parent': '1'}]

【问题讨论】:

  • 为什么要打印成str
  • db.session 是什么? SQL炼金术?如果是,您可能需要查看 SQLAlchemy 的文档。
  • @bruno desthuilliers 是的,db.session 是 SQLAlchemy。在文档中哪里可以看到返回数据的格式?
  • @Ambasador SQLAlchemy 是一个相当复杂的库,我对它没有太多经验,所以我无法回答,但根据这篇文章中的第一个答案(不是接受的答案)(@ 987654321@)、[dict(row) for row in locations)] 应该可以工作。话虽这么说,如果您使用的是 SQLAlchemy,最好花点时间阅读文档...

标签: python flask


【解决方案1】:

你可以试试下面的代码,这里 samp 可以是你的返回值。

final = []
for i in samp:
    row = {}
    row['id'] = i[0]
    row['name'] = i[1]
    row['code'] = i[2]
    row['id_parent'] = i[3]
    final.append(row)
print(final)

【讨论】:

  • 由于几乎所有符合 db-api 的连接器都有 DictCursor,因此肯定有更好的方法。
  • @Gaurang Patel 在不使用循环的情况下从数据库中采样时如何获得所需的数据格式?
  • @Ambasador 你可以用这个 print(json.dumps(response))
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 2020-05-07
  • 1970-01-01
  • 2018-08-11
  • 1970-01-01
  • 2014-11-19
  • 2018-03-26
  • 2016-12-12
相关资源
最近更新 更多