如何使用 PyGreSQL 接收通知?

How to receive notices with PyGreSQL?

我在 Postgres 9.5 中使用 PyGreSQL 4.1.1,并编写了一些存储函数。我将 RAISE 与函数内部的不同级别一起用于调试目的,这在 psql 中运行良好,但我还没有找到在 Python 中访问这些消息的方法。

示例:

CREATE OR REPLACE FUNCTION my_function()  RETURNS BOOLEAN AS $_$
    BEGIN
        RAISE NOTICE 'A notice from my function.';
        RETURN TRUE;
    END
$_$ LANGUAGE plpgsql;

我的 Python 代码如下所示:

conn = pgdb.connect(database = 'mydb', user = 'myself')
cursor = conn.cursor()
cursor.execute("SELECT my_function()"):

如何在 运行 my_function() 之后访问通知 (A notice from my function.)?

由于@klin 的评论,我发现了一个不太干净的解决方案。 pgdb.Connection 对象将基础 pg.Connection 对象存储在名为 _cnxprivate 属性 中。因此,您可以像这样设置通知接收器:

def my_notice_receiver(notice):
    logging.info("Notice: %s", notice)

conn._cnx.set_notice_receiver(my_notice_receiver)