在用JSON编码之前,如何将数据从SQLite数据库读入字典?

2024-03-28 13:57:59 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python和SQLite的初学者。所以请对我耐心点。我不太确定我应该提供多少信息,所以我决定尽可能多地编写我认为相关的代码。就像俗话说的,安全总比后悔好。在

基本上,我拥有的是一个python脚本,运行一个cherrypy服务器,用于一种点对点的社交网络web应用程序。我有一个方法可以记录我对个人资料的三种更新:新帖子、新照片或新事件。在

每个更新都包含以下字段:

messageID: A 16 letter string containing a unique identifier
creator: My user name
created: A time stamp, UNIX Epoch time, of when the update took place
body: A short message about the update.
Link: A link to the update. e.g.. "/gallery/photo5"
Type: type 1 means new post, 2 means photo, 3 means event.

我在用SQLite创建的数据库中,将这些字段变成表的列,我使用的方法如下:

^{pr2}$

我有另一个方法,我的朋友可以调用,以获取我最新更新的新闻源。这种方法是:

@cherrypy
def getActivity(self, minutes=48*60):
“”” Return any updates since last time this user requested them. Optional argument returns the last updates in the given time period instead.
“””
# current_user = getAuthenticatedUser(): # if not current_user:
# return “Please Authenticate”
# updates = getUpdatesByUser(current_user)

ExampleUpdate = [ {
‘messageID’: “ccog001-1332889924-839”, ‘creator’: “ccog001”,
‘created’: 1332889924,
‘link’: “/updates?id=839”,
‘type’: 1,
‘body’: “Hello, is anybody out there?”
},{
‘messageID’: “ccog001-1332890482-840”, ‘creator’: “ccog001”,
‘created’: 1332890482,
‘link’: “/updates?id=840”, ‘type’: 1,
‘body’: “Seriously, is this thing on?” }
]


reply = json.dumps(updates)
return reply

我的问题是,在用json.dumps?在

或者,如果我写下messageID,creator,created。。。等。。。先查字典,然后再把字典写进数据库?所以我的数据库只包含一列字典?如果是这样,代码会是什么样子?在

我很新,所以请在你的回答中详细说明,最好是用代码和注释来帮助我理解。在

非常感谢您抽出时间


Tags: the方法代码timetypelinkupdatebody
1条回答
网友
1楼 · 发布于 2024-03-28 13:57:59

在执行SELECT语句后,列名存储在Cursor.description中。根据docs,这个列表中的每个条目都是一个7元组,其中第一个元素由列的名称填充。在

您可以提取列名并形成dict,如下所示:

cur.execute('select * from Updates')

# extract column names
column_names = [d[0] for d in cur.description]

for row in cur:
  # build dict
  info = dict(zip(column_names, row))

  # dump it to a json string
  reply = json.dumps(info)

在这里,zip获取两个列表column_names和{},并将它们按元素顺序缝合到元组列表中。dict然后将其转换为一个字典,以便json进行转储。在

相关问题 更多 >