【发布时间】:2021-09-19 14:15:19
【问题描述】:
我正在尝试使 Postgress LISTEN 与 FastAPI 异步,以便在等待 Postgres 表更新时 WebSocket 连接不会阻塞。
到目前为止我得到了什么:
router = APIRouter()
@router.websocket("/pg_notify")
async def get_notifications(websocket: WebSocket):
await websocket.accept()
conn = psycopg2.connect("*****")
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
curs = conn.cursor()
curs.execute("LISTEN channel;")
while True:
try:
conn.poll()
while conn.notifies:
print("Waiting for notification...")
notify = await conn.notifies.pop(0)
print(notify.payload)
except Exception as e:
print("exception triggered: ", str(e))
await websocket.close()
这样会在 conn.notifies,pop(0) 上引发异常:
object psycopg2.extensions.Notify can't be used in the 'await' expression
【问题讨论】:
-
psycopg2不支持异步。看看aiopg 或psycopg3 (beta version, only)
标签: python websocket python-asyncio psycopg2 fastapi