Why I can't fetch responses from aiohttp in cycle? Exception: ValueError: I/O operation on closed file + aiohttp.payload.LookupError
Why I can't fetch responses from aiohttp in cycle? Exception: ValueError: I/O operation on closed file + aiohttp.payload.LookupError
当我试图从周期中的每个 api_key 获得响应时,我总是对两个错误感到困惑 - ValueError: I/O operation on closed file AND aiohttp.payload.LookupError...
async def get_api_response(photo_bytes, api_key, language):
async with aiohttp.ClientSession() as session:
async with session.post(URL_API,
data={
"picture.png": photo_bytes,
"apikey": api_key,
"language": language
}) as response:
return await response.text()
它是对 API
的异步请求的异步函数
for api_key in API_KEYS:
response = json.loads(await get_api_response(photo_bytes=photo_bytes, api_key=api_key, language=photo_lang))
print(response)
这是有结果的循环↑
但是当我尝试在函数中实现循环时 - 给出了相同的结果。但是当我在没有循环的情况下调用函数时 - 它起作用了!
如何通过最小的更改来解决这个问题?
UPD:在研究过程中,我注意到它发生在第一个周期后 PHOTO_BYTES 关闭 。
这里是初始化photo_bytes:
photo = cv2.imread(photo_path)
unused_var, compressed_image = cv2.imencode('.png', photo, [1, 90])
photo_bytes = io.BytesIO(compressed_image)
喜欢这样的东西
with io.BytesIO(compressed_image) as f:
photo_bytes = f.read()
当我试图从周期中的每个 api_key 获得响应时,我总是对两个错误感到困惑 - ValueError: I/O operation on closed file AND aiohttp.payload.LookupError...
async def get_api_response(photo_bytes, api_key, language):
async with aiohttp.ClientSession() as session:
async with session.post(URL_API,
data={
"picture.png": photo_bytes,
"apikey": api_key,
"language": language
}) as response:
return await response.text()
它是对 API
的异步请求的异步函数for api_key in API_KEYS:
response = json.loads(await get_api_response(photo_bytes=photo_bytes, api_key=api_key, language=photo_lang))
print(response)
这是有结果的循环↑
但是当我尝试在函数中实现循环时 - 给出了相同的结果。但是当我在没有循环的情况下调用函数时 - 它起作用了! 如何通过最小的更改来解决这个问题?
UPD:在研究过程中,我注意到它发生在第一个周期后 PHOTO_BYTES 关闭 。
这里是初始化photo_bytes:
photo = cv2.imread(photo_path)
unused_var, compressed_image = cv2.imencode('.png', photo, [1, 90])
photo_bytes = io.BytesIO(compressed_image)
喜欢这样的东西
with io.BytesIO(compressed_image) as f:
photo_bytes = f.read()