为什么我无法循环获取 aiohttp 的响应?异常:ValueError:对已关闭文件的 I/O 操作 + aiohttp.payload.LookupError
当我尝试在周期中从每个api_key获得响应时,我总是会与两个错误相混淆-valueRor:I/O在封闭文件和aiohttp.payload.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()
它的异步函数是ync andnc reqync请求对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关闭后发生的。
这是init photo_bytes:
photo = cv2.imread(photo_path)
unused_var, compressed_image = cv2.imencode('.png', photo, [1, 90])
photo_bytes = io.BytesIO(compressed_image)
When I tried to get response from each api_key in cycle I'm always confused with two errors - 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()
It`s async function for async requests to 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)
And this is cycle with results ↑
But when I tried to implement cycle in the function - gives the same result. But when I call function without cycle - it's work!
How can this be fixed with minimal changes?
UPD: DURING RESEARCH I'M NOTICED THAT IT'S OCCURES WHEN AFTER FIRST CYCLE PHOTO_BYTES CLOSE UP.
Here is init photo_bytes:
photo = cv2.imread(photo_path)
unused_var, compressed_image = cv2.imencode('.png', photo, [1, 90])
photo_bytes = io.BytesIO(compressed_image)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
像这样的东西
Like something like this
我也有类似的问题,其中我将一个
bytesio
对象传递给多个请求。问题似乎是AIOHTTP在使用它完成后关闭
bytesio
对象,因此我们无法使用另一个请求重复使用它。解决方案是每次将其传递给请求方法时创建
bytesio
对象。I had similar issue in which I pass one
BytesIO
object to multiple request.The problem seem to be that aiohttp closes the
BytesIO
object when it finished using it, so we can't reuse it with another request.The solution is to create
BytesIO
object every time I pass it to request method.