【发布时间】:2014-10-23 05:40:43
【问题描述】:
我有一个 Python http 服务器,它侦听基于 JSON 的请求。收到请求后,从 JSON 输入中解析 key,并查询具有该 key 的 Sqlite 数据库。现在我想用结果 JSON 消息响应请求。我是 Python 新手,不知道如何操作。
我的代码结构如下:
import ...
key=...;//get key from request
con = lite.connect('test.db')
with con:
con.row_factory = lite.Row
cur = con.cursor()
cur.execute("SELECT * FROM mytable ");
while True:
row = cur.fetchone()
if row == None:
break
if key==row['key']:
# How can I add the record to the response?
并且处理程序会这样写响应(在一个类中继承 BaseHTTPRequestHandler 并由一个线程启动)
self.send_response(200)
self.send_header('Content-Type', 'application/json')
self.end_headers()
self.wfile.write(??????) # What do I need to write here?
【问题讨论】:
-
导入json; self.wfile.write(json.dumps(yourdict))
-
@gosom 如何从 sqlite 结果/行中组织这样的字典?我使用 LocalData.records[row[0]]=row 存储每个匹配的行,并使用 self.wfile.write(json.dumps(LocalData.records)) 写入输出。它说“...不是 JSON 可序列化的”。