把单条数据变为字典
import aiopg
import asyncio
from sanic import Sanic, json
app = Sanic(name='test')
@app.listener('before_server_start')
async def setup_db_redis(app):
dsn = 'dbname=aiopg user=aiopg password=passwd host=127.0.0.1 port=5432'
app.ctx.pg = await aiopg.create_pool(dsn, minsize=2, maxsize=5, pool_recycle=3)
@app.get('/test')
async def test(request):
async with app.ctx.pg.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT * FROM public.test LIMIT 1;")
res = cur.description
columns_name = [i.name for i in res]
res = await cur.fetchall()
res_dict = dict(zip(columns_name, res[0]))
return json(res_dict)
app.run(host='127.0.0.1', port=8088, debug=True)
把多条数据变为字典
import aiopg
import asyncio
from sanic import Sanic, json
app = Sanic(name='test')
@app.listener('before_server_start')
async def setup_db_redis(app):
dsn = 'dbname=aiopg user=aiopg password=passwd host=127.0.0.1 port=5432'
app.ctx.pg = await aiopg.create_pool(dsn, minsize=2, maxsize=5, pool_recycle=3)
async def mresults(pool):
async with pool.acquire() as conn:
async with conn.cursor() as cur:
await cur.execute("SELECT * FROM public.test LIMIT 100;")
res = cur.description
columns_name = [i[0] for i in res]
res = await cur.fetchall()
res_dict = [dict(zip(columns_name, row_value)) for row_value in res]
return res_dict
@app.get('/test100')
async def test10(request):
tasks = []
for i in range(100):
task = asyncio.create_task(mresults(app.ctx.pg))
tasks.append(task)
res = await asyncio.gather(*tasks)
return json(res)
app.run(host='127.0.0.1', port=8088, debug=True)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧