首页 > 解决方案 > PythonShell.py:27: RuntimeWarning: coroutine 'get_info' 从未等待 mpl.use('AGG')

问题描述

我想将以下函数转换为异步函数以对 REST 端点进行异步调用:

def get_info(data, url, mini_batch = 1000):
  responses = []

  for first in range(0, len(data), mini_batch):
      data = data[first:first+mini_batch].tolist()

      input_json_data = json.dumps(data)

      headers = {'Content-Type': 'application/json'}

      resp = requests.post(url, input_json_data, headers=headers)
      responses.append(json.loads(resp.text).get('result'))

  output = numpy.concatenate([numpy.array(i) for i in responses])
  return output

我为 Python 3 找到了这些示例。这是我尝试过的:

import asyncio

asynch def get_info(data, url, mini_batch = 1000):

  await asyncio.sleep(1)

  responses = []

  async for first in range(0, len(data), mini_batch):
      data = data[first:first+mini_batch].tolist()

      input_json_data = json.dumps(data)

      headers = {'Content-Type': 'application/json'}

      resp = requests.post(url, input_json_data, headers=headers)
      responses.append(json.loads(resp.text).get('result'))

  output = numpy.concatenate([numpy.array(i) for i in responses])
  return output

然后我调用这个函数如下:

output = asyncio.run(get_info(data, url, mini_batch))

但我得到了错误:

TypeError: 'async for' requires an object with __aiter__ method, got range

怎么了?

更新:

这是我尝试使用以下建议的方法aiohttp

import aiohttp
import asyncio

async def fetch(session, url, headers, input_json_data):
    async with session.post(url, input_json_data, headers) as response:
        return await json.loads(response.text).get('result')


async def get_info(input_data, url):

  async with aiohttp.ClientSession() as session:
    input_json_data = json.dumps(input_data.tolist())
    headers = {'Content-Type': 'application/json'}
    output = await fetch(session, url, headers, input_json_data)

  return output

称呼:

asyncio.run(get_info(data, url))

或者

asyncio.gather(get_info(data, url))

错误:

PythonShell.py:27: RuntimeWarning: coroutine 'get_info' is never awaited mpl.use('AGG') RuntimeWarning: E​​nable tracemalloc to get the object allocation traceback TypeError: post() 接受 2 个位置参数,但给出了 4 个

或者

RuntimeError: There is no current event loop in thread 'MainThread'

标签: python-3.xasynchronouspython-asyncioaiohttp

解决方案


推荐阅读