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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.