Search code examples
pythonpython-3.xasynchronoussyntax-errorasyncpg

Python3 SyntaxError with asyncpg


I am trying to create a connection pool as shown on the documentation to test the module.

Here's my last attempt:

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")

I'm getting a SyntaxError on line 4, pointing at 'with':

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

Running the code from the Python interpreter on the terminal produces the same results.

Python version is 3.6.5, running the script from the terminal with python3 script.py


Solution

  • you should wrap your code inside an async function and call it inside loop , for example:

    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()
    

    more details: example-chain-coroutines