我使用aiohttp来构建一个API服务器,它将TCP请求发送到一个单独的服务器.发送TCP请求的模块是同步的,对于我来说是一个黑盒.所以我的问题是这些请求阻塞了整个API.我需要一种方法,将模块请求封装在一个异步协同路由中,这样就不会阻塞API的其余部分.

那么,仅以sleep为简单示例,是否有任何方法可以以某种方式将耗时的同步代码包装到非阻塞协同路由中,比如:

async def sleep_async(delay):
    # After calling sleep, loop should be released until sleep is done
    yield sleep(delay)
    return 'I slept asynchronously'

推荐答案

最终,我在this thread分中找到了答案.我想要的方法是run_in_executor.这允许同步函数异步运行,而不会阻塞事件循环.

在我上面发布的sleep个示例中,可能是这样的:

import asyncio
from time import sleep

async def sleep_async(loop, delay):
    # None uses the default executor (ThreadPoolExecutor)
    await loop.run_in_executor(None, sleep, delay)
    return 'I slept asynchronously'

Also see the following answer -> How do we call a normal function where a coroutine is expected?

Python-3.x相关问答推荐

Pandas 中每行的最大值范围

这是重命名极地df列的最好方式吗?

是否有必要使用Threads()中的args显式地将共享变量传递给Python中的线程函数或直接访问它?

在多个测试中维护和报告变量

如何在M x N数组的行中找到所有值的组合

为什么我在BLE中的广告代码在发送包裹之间需要大约1秒

找到在指定列的另一个分组中存在重复的行.

Pandas 转换为日期时间

将值从函数传递到标签

正则表达式来识别用 Python 写成单词的数字?

通过点和线计算CV2 Homography

Python defaultdict 在获取时返回 None,尽管使用默认值初始化

使用 python-binance 时,heroku [regex._regex_core.error: bad escape \d at position 7] 出错

将字节数组转换为类似字节的对象?

如何确定一个类的元类?

如何判断一个字符串是否包含有效的 Python 代码

如何通过命令行将数组传递给python

无论如何我可以在 Google colaboratory 中下载文件吗?

什么是ANSI_X3.4-1968编码?

Python:如何在 Windows 资源管理器中打开文件夹(Python 3.6.2、Windows 10)