Thread: python async with psycopg2

python async with psycopg2

From
Rita
Date:
I am trying to listen to multiple channels thru pg_notify mechanism.

select pg_notify('mychan0',foo');
select pg_notify('mychan'1,'bar');

In python I have something like this

import select,time
import psycopg2
import psycopg2.extensions
from psycopg2.extras import wait_select

DSN="dbname=mydb user=user host=localhost"

def main():

    conn = psycopg2.connect(DSN,async_=True)
    wait_select(conn)
    curs = conn.cursor()
    curs.execute("LISTEN mychan0;")
    #curs.execute("LISTEN mychan1;") #fails!
    wait_select(conn)
    while True:
        wait_select(conn)
        while conn.notifies:
            print("Notify: %s"%conn.notifies.pop().payload)
            time.sleep(1)
    conn.close()

I keep getting 

psycopg2.ProgrammingError: execute cannot be used while an asynchronous query is underway

I prefer to stick with psycopg2 library instead of a wrapper. 
What am I doing wrong?

--
--- Get your facts first, then you can distort them as you please.--

Re: python async with psycopg2

From
Daniele Varrazzo
Date:
On Fri, 17 Jul 2020 at 20:44, Rita <rmorgan466@gmail.com> wrote:>

>     curs = conn.cursor()
>     curs.execute("LISTEN mychan0;")
>     #curs.execute("LISTEN mychan1;") #fails!
>     wait_select(conn)

Maybe you have to wait_select after each execute.

This example could be helpful.
https://www.psycopg.org/docs/advanced.html#asynchronous-notifications
Note that you don't need an async connection to receive notification:
a sync one, as long as is in autocommit and you are using an I/O
completion function to wait for readiness, works as well.

-- Daniele