Psycopg cannot use the ‘ProactorEventLoop‘ to run in async mode. Please use a compatible event loop,
·
在Windows中将LangGraph的记忆存储在PostgreSQL数据库,编写Fastapi接口异步调用时出现报错:
Psycopg cannot use the ‘ProactorEventLoop’ to run in async mode. Please use a compatible event loop, for instance by running 'asyncio.run(…, loop_factory=asyncio.SelectorEventLoop(selectors.SelectSelector()))
ProactorEventLoop 是 Windows 上默认的事件循环,但它不适合所有异步库,尤其是那些依赖 select() 或需要特定异步 I/O 模型的库,比如 Psycopg(或者更准确地说,asyncpg 或 psycopg[binary] 在异步模式下)。
以下3种解决方法,先尝试前两种,如果无法解决再使用第三种
方法1
将下面的代码粘贴到main.py(Fastapi应用入口文件)中。
if __name__ == "__main__":
# --- 解决 ProactorEventLoop 问题的关键代码 ---
if platform.system() == "Windows":
asyncio.set_event_loop_factory(asyncio.SelectorEventLoop)
# ----------------------------------------
uvicorn.run("main:app", host="127.0.0.1", port=8002)
或者粘在import uvicorn之前
方法2
在导包的前面插入下面代码
if os.name == "nt": # 仅 Windows 需要
asyncio.set_event_loop_policy(
asyncio.WindowsSelectorEventLoopPolicy()
)
方法3
如果前两个方法都无法解决(我就是这样)
可以新建一个run.py文件,这样写:
# run.py —— 必须放在项目根目录,与 main.py 同级
import os
import asyncio
import sys
# 1. 在「任何 import 」之前就换策略
if os.name == "nt":
asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
# 2. 现在再导入 uvicorn,确保它内部拿到 Selector
import uvicorn
if __name__ == "__main__":
# 3. factory=True 强制子进程每次重启都重新执行本文件
uvicorn.run(
"main:create_app", # 用 factory 模式
host="127.0.0.1",
port=8002,
loop="asyncio",
reload=True,
factory=True,
)
这里的create_app是原来的main.py中创建app的函数,大致如下:
def create_app() -> FastAPI:
"""
创建FastAPI实例
"""
app = FastAPI(
title=settings.app_name,
description="FastAPI Demo",
version=settings.app_version,
lifespan=lifespan
)
app.include_router(auth_router, prefix="/api/v1", tags=["认证"])
app.include_router(order_router, prefix="/api/v1", tags=["订单"])
app.include_router(agent_router, prefix="/api/v1", tags=["智能体"])
return app
同时删掉main.py中的if name == “main”:,运行run.py即可。
亲测有效。
更多推荐



所有评论(0)