从 Python 中的 Sqlite 查询发送 JSON 响应

mrm*_*ent 6 python sqlite json

我有一个 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?
Run Code Online (Sandbox Code Playgroud)

并且处理程序将像这样编写响应(在类中继承 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?
Run Code Online (Sandbox Code Playgroud)

fre*_*ish 5

返回 JSON 响应就像这样简单:

import json
import sqlite3

def get_my_jsonified_data(key):
    with sqlite3.connect('test.db') as conn:
        cursor = conn.cursor()
        cursor.execute("SELECT * FROM mytable WHERE column=?;", [key])
        data = cursor.fetchall()
        return json.dumps(data)
Run Code Online (Sandbox Code Playgroud)

(假设这lite是 的别名sqlite3)

请注意其他一些事项:

  1. 我已经删除了while True:循环。它的效率极低、不安全且难以阅读;
  2. 我在 SQL 查询内部添加了检查key(为什么你要从数据库加载不必要的数据?)

  • @PrahladYeri 看来您正在某处使用 `conn.row_factory = sqlite3.Row` 。在这种情况下,您可以尝试“json.dumps([tuple(row) for row in data])”。 (5认同)

Azi*_*ziz 5

你可以试试这个

import sqlite3


def row_to_dict(cursor: sqlite3.Cursor, row: sqlite3.Row) -> dict:
    data = {}
    for idx, col in enumerate(cursor.description):
        data[col[0]] = row[idx]
    return data

with sqlite3.connect(db_path) as con:
    con.row_factory = row_to_dict
    result = con.execute('SELECT * FROM table_name')
    print(result.fetchall())

Run Code Online (Sandbox Code Playgroud)