python & postgresql: reliably check for updates in a specific table python & postgresql: reliably check for updates in a specific table multithreading multithreading

python & postgresql: reliably check for updates in a specific table


You can use notifications in postgresql:

import psycopg2from psycopg2.extensions import ISOLATION_LEVEL_AUTOCOMMITimport selectdef dblisten(dsn):    connection = psycopg2.connect(dsn)    connection.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)    cur = connection.cursor()    cur.execute("LISTEN new_id;")    while True:        select.select([connection],[],[])        connection.poll()        events = []        while connection.notifies:            notify = connection.notifies.pop().payload            do_something(notify)

and install a trigger for each update:

CREATE OR REPLACE FUNCTION notify_id_trigger() RETURNS trigger AS $$BEGIN  PERFORM pg_notify('new_id', NEW.ID);  RETURN new;END;$$ LANGUAGE plpgsql;CREATE TRIGGER data_modified AFTER insert or update on data_table for each row execute procedure notify_id_trigger();")