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)
返回 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)
请注意其他一些事项:
while True:循环。它的效率极低、不安全且难以阅读;key(为什么你要从数据库加载不必要的数据?)你可以试试这个
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)
| 归档时间: |
|
| 查看次数: |
9422 次 |
| 最近记录: |