It's currently possible to start asyncio servers by providing a callback that would fire on each incoming connection:
async def on_connection(reader, writer):
# this is invoked each time a new connection is made
pass
server = await asyncio.start_server(on_connection, host, port)
I would like to get rid of callback and use async for
instead, so it would look like this:
async for reader, writer in my_start_server(host, port):
# this should be invoked each time a new connection is made
pass
Unfortunately, it does not seem to be very easy:
async def my_start_server(host, port):
async def on_connection(reader, writer):
# here I have to somehow yield (reader, writer) tuple
# but if I do just `yield (reader, writer)`, it would
# make `on_connection` itself a generator, but would
# not affect `my_start_server`
pass
server = await asyncio.start_server(on_connection, host, port)
I have thought about having a class with __aiter__
implementation there, but result seems to be overcomplicated a lot. So, is this the only way to go, or am I missing any easy approaches on converting async callbacks to async generators?