【问题标题】:How to work with libraries that don't support async?如何使用不支持异步的库?
【发布时间】:2016-11-26 23:04:41
【问题描述】:

我正在从烧瓶转移到 aiohttp,我需要在不支持异步的 Oracle 数据库中执行一些查询。所以我想知道如何在 aiohttp 中做到这一点?

这个怎么样?

http://pastebin.com/nbWABbvK

或者还有其他(正确的)方法可以做到这一点?

提前致谢!

【问题讨论】:

  • 并非所有事情都需要异步。您可以像不使用 asyncio 一样使用该库。
  • 我必须以异步方式执行此操作,因为我的应用程序将被其他客户端阻止

标签: python-3.x async-await python-asyncio cx-oracle aiohttp


【解决方案1】:

loop.run_in_executor 协程正是这样做的:

result = await loop.run_in_executor(executor, sync_fn, *args)

使用您的示例:

executor = ThreadPoolExecutor(max_workers=1)

async def hello(request):
    param1, param2 = get_params(request)
    result = await app.loop.run_in_executor(executor, sync_fn, param1, param2)
    return web.Response(text=result)

【讨论】:

  • 是的,我明白了,但你没听懂,我用的是aiohttp,更新了示例代码
  • 我必须使用应用循环,而不是创建新循环?如果我将 None 作为执行程序传递,我已经阅读了源代码,它将为我创建带有 5 个工作人员的线程池执行程序!
  • @Howtochangeusername 当然,您一次只能运行一个循环。是的,默认执行者是 ThreadPoolExecutor,有 5 个工作人员。
  • 但我需要创建并传递新的执行程序,因为我不想使用应用程序执行程序的资源,或者没有就可以了?
  • @Howtochangeusername 使用默认的执行器非常好。
猜你喜欢
  • 2013-03-23
  • 1970-01-01
  • 2015-11-04
  • 2016-03-11
  • 1970-01-01
  • 2011-05-05
  • 2017-12-26
  • 2022-01-19
  • 2015-12-19
相关资源
最近更新 更多