0

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

Gugu72
  • 2,052
  • 13
  • 35
D. Hard
  • 21
  • 4

1 Answers1

2

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())
D. Hard
  • 21
  • 4
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Feb 23 '22 at 07:50