【问题标题】:why does the the connection cursor need to be readable for a psycopg2 notification listening loop为什么 psycopg2 通知侦听循环需要读取连接光标
【发布时间】:2021-12-23 03:33:43
【问题描述】:

psycopg2 提供some example code for using postgresql notify facilities

import select
import psycopg2
import psycopg2.extensions

conn = psycopg2.connect(DSN)
conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)

curs = conn.cursor()
curs.execute("LISTEN test;")

print "Waiting for notifications on channel 'test'"
while True:
    if select.select([conn],[],[],5) == ([],[],[]):
        print "Timeout"
    else:
        conn.poll()
        while conn.notifies:
            notify = conn.notifies.pop(0)
            print "Got NOTIFY:", notify.pid, notify.channel, notify.payload

select.select([conn],[],[],5) == ([],[],[]) 代码在做什么?

select.select 的文档表明我们正在努力确保conn 下的套接字“准备好读取”。

psycogp2 连接“准备好读取”是什么意思?

【问题讨论】:

    标签: python postgresql psycopg2


    【解决方案1】:

    conn.poll() 是一个非阻塞命令。如果没有可用的通知(或其他通讯),它仍然会立即返回,而无需执行任何操作。当在一个紧密的循环中完成时,这将是忙碌的等待,这很糟糕。它会烧毁整个 CPU 什么都不做,甚至可能破坏整个系统的稳定性。

    select 的意思是“礼貌地等待连接上的某些内容被读取(暗示 poll 可能有事情要做),或者等待 5 秒,以先发生者为准。如果您想无限期地等待消息要显示出来,只需从选择中删除,5。如果您想等待几个句柄中的第一个发生有趣的事情,您可以将它们全部放在选择列表中,而不仅仅是conn。

    【讨论】:

      猜你喜欢
      • 2012-02-12
      • 2021-05-02
      • 2013-05-02
      • 1970-01-01
      • 1970-01-01
      • 2015-05-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多