Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中从Sqlite查询发送JSON响应_Python_Json_Sqlite - Fatal编程技术网

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

在Python中从Sqlite查询发送JSON响应,python,json,sqlite,Python,Json,Sqlite,我有一个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 =

我有一个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并由线程启动的类中)


返回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)
(假设
lite
sqlite3
的别名)

请注意以下几点:

  • 我已删除
    而为True:
    循环。它的效率极低,不安全,更难阅读
  • 我在SQL查询中添加了检查
    key
    (为什么还要从DB加载不必要的数据?)

  • 导入json;self.wfile.write(json.dumps(yourdict))@gosom如何从sqlite结果/行组织这样的dict?我使用LocalData.records[row[0]]=row存储每个匹配的行,并使用self.wfile.write(json.dumps(LocalData.records))写入输出。它说“…不是JSON可序列化的”。谢谢。对于键的检查,这是我的错,因为我正在逐段添加代码,所以这显然是不必要的(只需使用sql)。另一个问题是fetchall()可能会有问题(内存、响应大小等)。如果结果很大?@mrmoment除非您正在进行流式处理(看起来不是这样),否则您必须将所有数据加载到内存中。如果您正在进行流式处理,则使用cursor.fetchamany(10000)作为示例。逐项抓取的效率非常低。明白了。我想我可以使用“limit”子句来减少fetchall()的结果。再次感谢。当我在Python3中尝试这一点时,我得到了
    TypeError:type'Row'的对象在JSON.dumps(数据)上不是JSON可序列化的。您还需要配置其他内容吗?@PrahladYeri您似乎在某处使用
    conn.row\u factory=sqlite3.row
    。在这种情况下,您可以尝试
    json.dumps([tuple(row)表示数据中的行])
    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)