python3 asyncio 不阻塞_python – 使用asyncio和aiohttp的多个非阻塞任务

我试图用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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值