【问题标题】:aiohttp monkey patch to work with nest_asyncio与nest_asyncio一起使用的aiohttp猴子补丁
【发布时间】:2020-10-03 13:02:36
【问题描述】:

我在我的 python 项目中使用了nest_asyncio。一切都很完美,除了aiohttp 函数get_running_loop 有一些警告消息填满了我的所有日​​志。

aiohttp 为他们的get_running_loop 使用了类似的实现:

def get_running_loop(loop=None):
    if loop is None:
        loop = asyncio.get_event_loop()
    if not loop.is_running():
        warnings.warn("The object should be created from async function",
                                 DeprecationWarning,
                                 stacklevel=3)

在最后的版本中,他们甚至抛出异常:

def get_running_loop() -> asyncio.AbstractEventLoop:
    loop = asyncio.get_event_loop()
    if not loop.is_running():
        raise RuntimeError(
            "The object should be created within an async function"
        )
    return loop

但是 nest_asyncio loop is_running 方法永远不会返回 True 以不阻止 run_until_complete 的嵌套调用。

我尝试在其他类似这样的导入之前做一个猴子补丁:

import aiohttp.helpers

def _get_running_loop(loop=None):
    if loop is None:
        loop = asyncio.get_event_loop()
    return loop

aiohttp.helpers.get_running_loop = _get_running_loop

在所有导入之后,我看到aiohttp.helpers.get_running_loop 指向我的实现。但是 aiohttp 函数的调用仍然使用自己的实现(因为相对导入或其他原因):

async with aiohttp.ClientSession() as session:

打印到日志:

  The object should be created from async function
  File ".../lib/python3.7/site-packages/aiohttp/client.py", line 225, in __init__
    cookie_jar = CookieJar(loop=loop)
  File ".../lib/python3.7/site-packages/aiohttp/cookiejar.py", line 55, in __init__
    super().__init__(loop=loop)
  File ".../lib/python3.7/site-packages/aiohttp/abc.py", line 146, in __init__
    self._loop = get_running_loop(loop)
  File ".../lib/python3.7/site-packages/aiohttp/helpers.py", line 276, in get_running_loop
    stack_info=True)

我不想为此分叉所有 aiohttp 或分析 nest_asyncio 中的调用堆栈以对 aiohttp 有特殊响应。是否有可能在这里有一个简单的解决方案,比如猴子补丁,我如何修补在 asyncio 中使用的get_running_loop

【问题讨论】:

    标签: python-3.x aiohttp nest-asyncio


    【解决方案1】:

    我猜你还需要猴子补丁 abc 模块:

    import aiohttp.abc
    aiohttp.abc.get_running_loop = _get_running_loop
    

    在 vaex 中,我做了类似于 scikit-learn 的操作,但通过检查所有模块,请参阅 https://github.com/vaexio/vaex/blob/95aecc9ae1a4285babd42a104d64ed52b5130d2d/packages/vaex-ml/vaex/ml/__init__.py#L284

    【讨论】:

      猜你喜欢
      • 2016-09-01
      • 2012-09-16
      • 2012-12-18
      • 2020-01-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-29
      相关资源
      最近更新 更多