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

问题描述 投票:0回答:1

我开始使用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行)时,我的视图功能将按预期工作。有什么问题吗?

python aiohttp asyncpg
1个回答
0
投票

您需要使用await进行async呼叫;这是有关如何从池中获取连接,运行查询并将连接释放回池中的代码段

conn = await pg.acquire()
try:
    result = await conn.fetch("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)
© www.soinside.com 2019 - 2024. All rights reserved.