我想将以下函数转换为异步函数以对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
我发现these examples用于Python3。这是我尝试过的:
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:协程“ get_info”为 从未等待mpl.use('AGG')RuntimeWarning:启用tracemalloc来 获取对象分配回溯TypeError:post()需要2 位置参数,但给出了4个
或
RuntimeError: There is no current event loop in thread 'MainThread'