Why I can't fetch responses from aiohttp in cycle? Exception: ValueError: I/O operation on closed file + aiohttp.payload.LookupError

Question:

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)
Asked By: Sasha Zuev

||

Answers:

Like something like this

with io.BytesIO(compressed_image) as f:
    photo_bytes = f.read()
Answered By: Sasha Zuev

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.

Answered By: witoong623