为什么连接光标需要对 psycopg2 通知侦听循环可读
why does the the connection cursor need to be readable for a psycopg2 notification listening loop
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 连接“准备好读取”是什么意思?
conn.poll() 是一个非阻塞命令。如果没有可用的通知(或其他通讯),它仍然会立即 return,只是没有做任何事情。当在一个紧密的循环中完成时,这将是忙于等待,这很糟糕。它会燃烧整个 CPU 无所事事,甚至可能破坏整个系统。
select 的意思是“礼貌地等待连接上的内容被读取(暗示 poll 可能有事情要做),或者等待 5 秒,以先发生者为准。如果你想要要无限期地等待消息出现,只需从 select 中删除 ,5
。如果您想等待一些有趣的事情发生在几个句柄的第一个上,您可以将它们全部放在select 列表,不仅仅是 conn
.
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 连接“准备好读取”是什么意思?
conn.poll() 是一个非阻塞命令。如果没有可用的通知(或其他通讯),它仍然会立即 return,只是没有做任何事情。当在一个紧密的循环中完成时,这将是忙于等待,这很糟糕。它会燃烧整个 CPU 无所事事,甚至可能破坏整个系统。
select 的意思是“礼貌地等待连接上的内容被读取(暗示 poll 可能有事情要做),或者等待 5 秒,以先发生者为准。如果你想要要无限期地等待消息出现,只需从 select 中删除 ,5
。如果您想等待一些有趣的事情发生在几个句柄的第一个上,您可以将它们全部放在select 列表,不仅仅是 conn
.