python 3.x - Calling coroutine and getting future in asyncio.Protocol.data_received()? -
i need future result inside asyncio loop, similar calling coroutine asyncio.protocol.data_received
but asyncio
in py35 , py34 different, here code run correctly in py34, in py35 pause @ yield from
, never return.
# py34 class relayclient(asyncio.protocol): pass class server(asyncio.protocol): def data_received(self, data): # need connect address, , future result @ current function. # not run loop.run_until_complete(). loop = asyncio.get_event_loop() result = yield loop.create_connection(relayclient, 'www.google.com', 443) do_some_thing_with_result(result)
so, how in python 3.5?
any advice appreciated.
you cannot await coroutine function not coroutine. data_received
not coroutine, mentioned in comments, need use ensure_future
helper create "background" task coroutine.
no need start using callbacks however:
async def do_stuff(data): result = await loop.create_connection(relayclient, 'www.google.com', 443) await do_some_thing_with_result(result) class server(asyncio.protocol): def data_received(self, data): asyncio.ensure_future(do_stuff(data))
i point out however, asyncio gives no garanties whatsoever data_received
called complete data expecting. pattern see in protocol
looks lot this:
async def process_line(line): ... class server(asyncio.protocol): def __init__(self): self.buffer = b'' def data_received(self, data): self.buffer += data if b'\n' not in self.buffer: return line, self.buffer = self.buffer.split(b'\n') fut = asyncio.ensure_future(process_line(line)) fut.add_done_callback(self._handle_exception) def _handle_exception(self, fut): if fut.exception() not none: print('processing failed', fut.exception())
(this example, copies buffer way , inefficient in production use-cases)
Comments
Post a Comment