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

cgvd09ve  于 2023-06-23  发布在  SQLite
关注(0)|答案(3)|浏览(180)

我有一个Python http服务器,它监听基于JSON的请求。在接收到请求之后,它从JSON输入中解析出键,并查询具有这样的键的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?
zbdgwd5y

zbdgwd5y1#

返回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)

(假设litesqlite3的别名)
注意其他几点:
1.我删除了while True:循环。它的效率低得可怕,不安全,更难阅读;
1.我已经在SQL查询中添加了key的检查(为什么你要从DB加载不必要的数据呢?)

x7yiwoj4

x7yiwoj42#

你可以试试这个

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())
fcg9iug3

fcg9iug33#

显然还没有足够的分数来评论。@freakish -是的,我使用conn.row_factory = sqlite3.Row将结果作为python字典,是的,你的解决方案确实有效,但它没有将结果编码为一个字典列表,使用我需要的列名。
在Essense中,问题在于SQLite返回的SQLite对象是json.dumps无法处理的。我需要一种方法来创建一个像这样的3行输出:

{
'json': [
         {'column1': value, 'column2': value, 'column3': value},
         {'column1': value, 'column2': value, 'column3': value},
         {'column1': value, 'column2': value, 'column3': value}
        ]
}

我相信这个会做到的,但不像你的1班轮那么干净:)

rows = []
for row in data:
    cols = {}
    for col in row.keys():
        cols[col] = row[col]
    rows.append(cols)
jsn = json.dumps(rows)

相关问题