79279813

Date: 2024-12-13 23:46:08
Score: 0.5
Natty:
Report link

I've get an error AttributeError: 'str' object has no attribute 'pid'
small fix in order to run it: notify = connection.notifies.pop().payload -> notify = connection.notifies.pop()

Here is a full example that was taken from documentation and a bit changed, it is without timeout, thanks @snakecharmerb for link listen.py

import select

import psycopg2.extensions

CHANNEL = 'process'
# DSN = f'postgresql://{USER}:{password}@{HOST}/{DBNAME}'


def listen():
    curs = conn.cursor()
    curs.execute(f"LISTEN {CHANNEL};")

    print("Waiting for notifications on channel 'test'")
    while True:
        select.select([conn], [], [], 5)
        conn.poll()
        while conn.notifies:
            notify = conn.notifies.pop(0)
            print("Got NOTIFY:", notify.pid, notify.channel, notify.payload)


if __name__ == '__main__':
    conn = psycopg2.connect(host=HOST, dbname=DBNAME, user=USER, password=PASSWD)
    # conn = psycopg2.connect(DSN) # alternative connection
    conn.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT)
    listen()
  1. Run listener python listen.py
  2. Via pgAdmin Query Tool or Postgres Shell run select pg_notify('process', 'update'); or just NOTIFY process, 'This is the payload';

note: it should be the same DB, for listener and notifier

Reasons:
  • Blacklisted phrase (0.5): thanks
  • Long answer (-1):
  • Has code block (-0.5):
  • User mentioned (1): @snakecharmerb
  • Low reputation (0.5):
Posted by: akpp