Question about asyncio and blocking operations

Frank Millman frank at chagford.com
Fri Jan 29 03:53:32 EST 2016


"Frank Millman"  wrote in message news:n8et0d$hem$1 at ger.gmane.org...

> I have read the other messages, and I can see that there are some clever 
> ideas there. However, having found something that seems to work and that I 
> feel comfortable with, I plan to run with this for the time being.

A quick update.

Now that I am starting to understand this a bit better, I found it very easy 
to turn my concept into an Asynchronous Iterator.

class AsyncCursor:
    def __init__(self, loop, sql):
        self.return_queue = asyncio.Queue()
        request_queue.put((self.return_queue, loop, sql))

    async def __aiter__(self):
        return self

    async def __anext__(self):
        row = await self.return_queue.get()
        if row is not None:
            return row
        else:
            self.return_queue.task_done()
            raise StopAsyncIteration

The caller can use it like this -

    sql = 'SELECT ...'
    cur = AsyncCursor(loop, sql)
    async for row in cur:
        print('got', row)

Frank





More information about the Python-list mailing list