无法使用异步 psycopg3 连接 postgres 数据库:
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())
我收到错误:
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())'
在 Windows 10、Python 3.9、Psycopg 3.0.8 上
这是工作解决方案
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())