我试图用asyncio和aiohttp执行几个非阻塞任务,我不认为我这样做是有效的.我认为最好使用await而不是yield.有人可以帮忙吗?
def_init__(self):
self.event_loop = asyncio.get_event_loop()
def run(self):
tasks = [
asyncio.ensure_future(self.subscribe()),
asyncio.ensure_future(self.getServer()),]
self.event_loop.run_until_complete(asyncio.gather(*tasks))
try:
self.event_loop.run_forever()
@asyncio.coroutine
def getServer(self):
server = yield from self.event_loop.create_server(handler, ip, port)
return server
@asyncio.coroutine
def sunbscribe(self):
while True:
yield from asyncio.sleep(10)
self.sendNotification(self.sub.recieve())
def sendNotification(msg):
# send message as a client
我必须听一个服务器并订阅收听广播,并根据广播的消息POST到另一台服务器.
最佳答案 根据 PEP 492:
await , similarly to yield from , suspends execution of read_data
coroutine until db.fetch awaitable completes and returns the result
data.It uses the yield from implementation with an extra step of validating
its argument. await only accepts an awaitable , which can be one of:
所以我没有在代码中看到效率问题,因为它们使用相同的实现.
但是,我确实想知道为什么要返回服务器但从不使用它.
我在你的代码中看到的主要设计错误是你使用两者:
self.event_loop.run_until_complete(asyncio.gather(*tasks))
try:
self.event_loop.run_forever()
从我所看到的你只需要run_forever()
一些额外的提示:
在我使用asyncio的实现中,我通常会确保在出现错误时关闭循环,否则这会导致大量泄漏,具体取决于您的应用类型.
try:
loop.run_until_complete(asyncio.gather(*tasks))
finally: # close the loop no matter what or you leak FDs
loop.close()
我也使用Uvloop而不是内置的,根据基准测试它更有效率.
import uvloop
...
loop = uvloop.new_event_loop()
asyncio.set_event_loop(loop)