当我在aiohttp应用程序中使用asyncpg时出现了奇怪的错误

2024-10-04 03:26:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我开始用aiopg开发我的应用程序来访问postgres中的数据,一切都很好,我决定用asyncpg代替它

这是我的查看功能之一:

@router.get('/{post}')
@aiohttp_jinja2.template("view.html")
async def view_post(request):
    ret = {'id':'1','owner':'shooooobi','editor':'shooooobi','title':'new_title','text':'nothing'}

    return {"post":ret}

这是一个简单的视图,还可以,但当我添加一些类似下面的asyncpg代码时,我逐行添加了第4行到第7行并运行应用程序

@router.get('/{post}')
@aiohttp_jinja2.template("view.html")
async def view_post(request):
    pg  = request.config_dict["PG"]
    post_id = request.match_info["post"]
    con = pg.acquire()
    cur = con.cursor('SELECT id, owner, editor, title, text FROM mshma.posts where id=$1',post_id)
    ret = {'id':'1','owner':'shooooobi','editor':'shooooobi','title':'new_title','text':'nothing'}

    return {"post":ret}

第7行是因为我在我的网页中收到了以下文本

context should be mapping, not <class 'set'>

当我对这一行(第7行)进行注释时,我的视图功能按预期工作。 有什么问题吗


Tags: text功能viewid应用程序gettitlerequest
2条回答

您需要为异步调用使用await;下面是一个关于如何从池中获取连接、运行查询并将连接释放回池的代码段

conn = await pg.acquire()
try:
    result = await conn.fetchrow("SELECT id, owner, editor, title, text FROM mshma.posts where id=$1", post_id)
finally:
    await pg.release(conn)
# do something with result (which is an asyncpg.Record object)

执行此查询失败,因为参数id列为整数,参数post\U id为字符串,所以在使用jinja2模板时不会显示错误!!。 我们只需要将post_id转换为整数(int(post_id)

相关问题 更多 >