'Psycopg3 unable to connect async

Unable to connect postgres database using async psycopg3 :

import asyncio
import psycopg

async def main():
    async with await psycopg.AsyncConnection.connect('postgresql://xxxxxxxxxxx') as con:
        async with con.cursor() as cur:
            print(await cur.execute('select 1 a').fetchall())

if __name__ == '__main__':
    asyncio.run(main())

I get error:

psycopg.InterfaceError: Psycopg cannot use the 'ProactorEventLoop' to run in async mode. Please use a compatible event loop, for instance by setting 'asyncio.set_event_loop_policy(WindowsSelectorEventLoopPolicy())'

On Windows 10, Python 3.9, Psycopg 3.0.8



Solution 1:[1]

Here is the working solution

import asyncio
import sys

import psycopg


async def main():

    async with await psycopg.AsyncConnection.connect('postgresql://xxxxxxxxxxx') as con:
        async with con.cursor() as cur:
            print(await (await cur.execute('select 1 a')).fetchall())

if __name__ == '__main__':

    if sys.platform == "win32":
        asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())

    asyncio.run(main())

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 D. Hard