Search code examples
pythonpython-2.7postgresqlpgdb

How to receive notices with PyGreSQL?


I'm using PyGreSQL 4.1.1 with Postgres 9.5, and have written some stored functions. I use RAISE with different levels inside of the functions for debugging purposes, which works very well in psql, but I haven't found a way to access those messages in Python.

Example:

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

My Python code looks like this:

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

How can I access the notice (A notice from my function.) after running my_function()?


Solution

  • Due to @klin's comment I found a somewhat unclean solution. The pgdb.Connection object stores the underlying pg.Connection object in a private property named _cnx. Thus, you can set the notice receiver like this:

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