Data driven applications are a good concept to keep in mind when design an application, especially when that application needs to have new bits added to it on a regular basis. My idea for using Python to listen for FreshPorts events is a case in point.
I’ve decided to go with a table like this:
create table listen_for ( id serial not null, name text not null, script_name text not null, primary key (id) ); create unique index listen_for_name_idx on listen_for (name);
The table contents looks like this:
freshports.org=# select * from listen_for; id | name | script_name ----+----------------+----------------------- 1 | port_updated | listen_port 2 | ports_moved | listen_ports_moved 3 | ports_updating | listen_ports_updating 4 | vuxml | listen_vuxml (4 rows) freshports.org=#
The script from previous posts now looks like this:
#!/usr/bin/env python # # This program listens for events on the database and processes them # # # configuration items # DSN = 'dbname=freshports.org user=dan' import sys, psycopg, select print "Opening connection using dns:", DSN conn = psycopg.connect(DSN) conn.autocommit(1) curs = conn.cursor() curs.execute("SELECT id, name, script_name FROM listen_for ORDER BY id"); listens_for = curs.fetchall() for listen in listens_for: curs.execute("LISTEN %s" % listen) print "Waiting for 'NOTIFY test'" while 1: select.select([curs],,)==(,,) curs.execute("SELECT 1") notifies = curs.notifies() for n in notifies: # in real life, do something with each... print n
This is pretty easy. I won’t have to alter this script much, if at all, when adding a new notification to the system. I may just have to HUP it or restart it.