python-3.x - 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: Enable tracemalloc to get the object allocation traceback TypeError: post() 接受 2 个位置参数,但给出了 4 个
或者
RuntimeError: There is no current event loop in thread 'MainThread'
解决方案
推荐阅读
- security - 如何使用 Gatsby 存储和访问 API 密钥和密码?
- r - 合并R中两个df之间的信息
- javascript - 将 react native web 添加到 react native 项目时出错
- typescript - 连接通用打字稿数组时出错
- android - 为什么 iOS 上的 Flutter 不能从 URL 播放音频文件,而只能从 IP 地址播放?
- javascript - 如何通过ng2-charts angular使用chartJs的自定义渲染方法?
- javascript - Svelte/yrv 路由器:如何访问组件中的路由器参数?
- java - 无法访问在 WebView 中工作的摄像头和麦克风
- android - 在 if 语句中使用数组值而不是 checkbox_id
- c# - 如果我将 null 分配给对象或属性,C# 中的垃圾收集器会始终运行并释放其内存空间吗?