问题描述
我在新的Python asyncio 模块的asyncio.Protocol.data_received
回调中做异步处理时遇到问题.
I am having a problem doing asynchronous stuff in the asyncio.Protocol.data_received
callback of the new Python asyncio module.
考虑以下服务器:
class MathServer(asyncio.Protocol):
@asyncio.coroutine
def slow_sqrt(self, x):
yield from asyncio.sleep(1)
return math.sqrt(x)
def fast_sqrt(self, x):
return math.sqrt(x)
def connection_made(self, transport):
self.transport = transport
#@asyncio.coroutine
def data_received(self, data):
print('data received: {}'.format(data.decode()))
x = json.loads(data.decode())
#res = self.fast_sqrt(x)
res = yield from self.slow_sqrt(x)
self.transport.write(json.dumps(res).encode('utf8'))
self.transport.close()
与以下客户端一起使用:
used with the following client:
class MathClient(asyncio.Protocol):
def connection_made(self, transport):
transport.write(json.dumps(2.).encode('utf8'))
def data_received(self, data):
print('data received: {}'.format(data.decode()))
def connection_lost(self, exc):
asyncio.get_event_loop().stop()
调用self.fast_sqrt
后,一切都会按预期进行.
With self.fast_sqrt
being called, everything works as expected.
对于self.slow_sqrt
,它不起作用.
它还不能与self.fast_sqrt
和data_received
上的@asyncio.coroutine
装饰器一起使用.
It also does not work with self.fast_sqrt
and the @asyncio.coroutine
decorator on data_received
.
我觉得这里缺少基本的东西.
I feel I am missing something fundamental here.
完整的代码在这里:
- Server
- Client
经过测试:
- Python 3.4.0b1(Windows)
- Python 3.3.3 + asyncio-0.2.1(FreeBSD)
问题在两个方面都是相同的:使用slow_sqrt
,客户端/服务器将挂起而无所事事.
The issue is the same on both: with slow_sqrt
, the client/server will just hang doing nothing.
推荐答案
看来,这需要通过Future
解耦-尽管我仍然不确定这是否是正确的方法.
It seems, this needs to be decoupled via a Future
- though I am still not sure if this is the right way.
class MathServer(asyncio.Protocol):
@asyncio.coroutine
def slow_sqrt(self, x):
yield from asyncio.sleep(2)
return math.sqrt(x)
def fast_sqrt(self, x):
return math.sqrt(x)
def consume(self):
while True:
self.waiter = asyncio.Future()
yield from self.waiter
while len(self.receive_queue):
data = self.receive_queue.popleft()
if self.transport:
try:
res = self.process(data)
if isinstance(res, asyncio.Future) or \
inspect.isgenerator(res):
res = yield from res
except Exception as e:
print(e)
def connection_made(self, transport):
self.transport = transport
self.receive_queue = deque()
asyncio.Task(self.consume())
def data_received(self, data):
self.receive_queue.append(data)
if not self.waiter.done():
self.waiter.set_result(None)
print("data_received {} {}".format(len(data), len(self.receive_queue)))
def process(self, data):
x = json.loads(data.decode())
#res = self.fast_sqrt(x)
res = yield from self.slow_sqrt(x)
self.transport.write(json.dumps(res).encode('utf8'))
#self.transport.close()
def connection_lost(self, exc):
self.transport = None
此处是Guido van的 answer 罗森(Rossum):
Here is an answer by Guido van Rossum:
def data_received(self, data):
asyncio.ensure_future(self.process_data(data))
@asyncio.coroutine
def process_data(self, data):
# ...stuff using yield from...
Full code is here: - Client - Server
这篇关于在asyncio.Protocol.data_received中调用协程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!