Reputation: 61
I am getting this error while sending a list of requests. I have found many other Q&As in stackoverflow with similar problems, but all answers say to use the ClientSession context. Which is exactly what I am doing here, but I still get this error:
ERROR - Unclosed client session, client_session: <aiohttp.client.ClientSession object at 0x7f95c1ca37f0>
I also tried to explicitly put "await session.close()" at the end, but this error still persists. My code snippet:
async def post_request(session, payload):
await asyncio.sleep(0.5)
headers = {'Authorization':"Bearer " + token,'Content-Type':'application/json'}
async with session.post(
url=URL,
headers=headers,
data=json.dumps(payload)) as resp:
print(f'Request sent with status: {resp.status}')
return resp.status
async def send_many(payload_list):
tasks = []
async with ClientSession(raise_for_status=True) as session:
for payload in payload_list:
tasks.append(asyncio.ensure_future(post_request(session=session,payload=payload)))
return await asyncio.gather(*tasks)
results=asyncio.run(send_many(payload_list))
print(results)
Upvotes: 1
Views: 4168
Reputation: 2863
This may or may not be the problem but I think you might need to await the response like this:
async def post_request(session, payload):
await asyncio.sleep(0.5)
headers = {'Authorization':"Bearer " + token,'Content-Type':'application/json'}
async with session.post(
url=URL,
headers=headers,
data=json.dumps(payload)) as resp:
print(f'Request sent with status: {resp.status}')
await resp.text() # Or `await resp.json()`
return resp.status
Upvotes: 2