带有asyncpg的Python3 SyntaxError

时间:2018-07-13 09:48:16

标签: python python-3.x asynchronous syntax-error asyncpg

我正在尝试创建一个the documentation所示的连接池来测试该模块。

这是我的最后尝试:

import asyncpg
cs = "user:password@my_postgresql_server_ipaddr:port/database?name=db_name"

async with asyncpg.create_pool(dsn=cs) as pool:
    print("pool created")

我在第4行收到SyntaxError,指向“ with”:

async with asyncpg.create_pool(dsn=cs) as pool:
         ^
SyntaxError: invalid syntax

在终端上运行Python解释器中的代码会产生相同的结果。

Python版本为3.6.5,使用python3 script.py从终端运行脚本

1 个答案:

答案 0 :(得分:1)

您应将代码包装在async函数中,并在loop内部调用,例如:

import asyncio
import asyncpg

async def test():
    cs = "user:password@my_postgresql_server_ipaddr:port/database?name=db_name"
    async with asyncpg.create_pool(dsn=cs) as pool:
        print("pool created")

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(test())
    loop.close()

更多详细信息:example-chain-coroutines