0

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

4

2 回答 2

0

您需要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)

于 2020-05-08T20:35:21.223 回答
0

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

于 2020-05-13T09:17:28.533 回答