'Postgres notification

How to get LISTEN or NOTIFY in PostgreSQL?

I tried to do it in PostgreSQL Console like this but it completed without any return:

LISTEN users_table;
NOTIFY users_table;

With Console return:

ub_test.users> LISTEN users
[2022-05-18 03:57:37] completed in 1 ms
ub_test.users> NOTIFY users
[2022-05-18 03:57:38] completed in 2 ms

Anyway I need to do it in my Python project and tried with this code:

def notify_changes(schema_name, table_name):
    conn = get_connection()
    conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
    cur = conn.cursor()

    sql = f"LISTEN {table_name};"

    cur.execute(sql)

    return conn

P.S. I tried to use schema_name instead of table_name cause idk which is correctly

def notify():
    ret = notify_changes('users', 'users_table')

    while True:
        if select.select([ret], [], [], 5) == ([], [], []):
            print("Timeout")
        else:
            ret.poll()
            while ret.notifies:
                notification = ret.notifies.pop(0)
                print(f"{notification.pid=}, {notification.channel=}, {notification.payload=}")

And I always get same return:

Timeout
Timeout
Timeout
Timeout

How to do it right?



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source