I have a simple postgres database, here's an example table
| id | created_at | whatever |
|---|---|---|
| 1 | 2020-12-22 21:47:20.159781 | something |
| 2 | 2020-12-22 22:13:46.872718 | anything |
how can I do that whenever something changes in it, it triggers a function in my script?
Postgres has the notify and listen procedures you can read up on here: notify and listen. Their use in Python is best (and I believe only) through pyscopg2
pip install psycopg2
import select
import psycopg2
import psycopg2.extensions
cnct = psycopg2.connect(DSN)
cnct.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
cursor = cnct.cursor()
cursor.execute("LISTEN channel;")
print("Pending notification from 'channel'...")
while True:
if select.select([cnct],[],[],5) == ([],[],[]):
print("Channel timed out.")
else:
cnct.poll()
while cnct.notifies:
notif = cnct.notifies.pop(0)
print("Received NOTIFY:", notif.pid, notif.channel, notif.payload)
Forgot to mention!: This information was from what I versed myself with on the Psycopg2 Documentation and you might need to more elaborately familiarize yourself with using Pyscopg2 there.
asyncpg.add_listener, I'm not sure tho
last_modifiedcolumn in your table, and fetching rows that have been modified since the last time you checked). Postgres does support calling PG_SQL functions when tables are modified, but I don't know off the top of my head how you would get those to trigger your python code.