python - 使用 asyncio 和 aiohttp 的多个非阻塞任务

标签 python async-await 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:

所以我在您的代码中没有看到效率问题,因为它们使用相同的实现。

但是,我确实想知道为什么您返回 server 却从未使用过它。

我在您的代码中看到的主要设计错误是您同时使用了两者:

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)

关于python - 使用 asyncio 和 aiohttp 的多个非阻塞任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43939824/

相关文章:

python - 异步运行时错误 : Event Loop is Closed

python - 如何防止 asyncio.Task 被取消

python - 如何准备一个包含整数、 float 和字符串的列表?

python - super 应该始终位于 __init__ 方法的顶部,还是可以位于底部?

python - 我收到此错误 : TypeError: object() takes no parameters

c# - System.Threading.Tasks 中的 NullReferenceException 调用 HttpClient.GetAsync(url)

javascript - 在 Node 中处理嵌套异步等待调用的正确方法是什么?

c# - 将同步代码包装到异步调用中

python - 嵌套正则表达式

python - aiohttp 与 asyncio 和信号量返回一个填充 None 的列表