I am making a discord bot with python. When a user types a command, this bot brings data from url and shows it. I use aiohttp
for asynchronous http request, but documentation of discord.py
says,
Since it is better to not create a session for every request, you should store it in a variable and then call
session.close
on it when it needs to be disposed.
So i changed all my codes from
async with aiohttp.ClientSession() as session:
async with session.get('url') as response:
# something to do
into
# Global variable
session = aiohttp.ClientSession()
async with session.get('url') as response:
# something to do
All http requests use globally defined session
. But when i run this code and stop by keyboard interrupt(Ctrl + C), this warning messages are appeared.
Unclosed client session
client_session: <aiohttp.client.ClientSession object at 0x0000015A45ADBDD8>
Unclosed connector
connections: ['[(<aiohttp.client_proto.ResponseHandler object at 0x0000015A464925E8>, 415130.265)]']
connector: <aiohttp.connector.TCPConnector object at 0x0000015A454B3320>
How can i close ClientSession
when program stops by keyboard interrupt?
What I tried:
I tried following but nothing worked well.
- Making a class and close in its
__del__
.__del__
was not called when keyboard interrupt.
class Session:
def __init__(self):
self._session = aiohttp.ClientSession()
def __del__(self):
self._session.close()
- Infinite loop in
main
, and catchKeyboardInterrupt
. Program is blocked withbot.run()
so cannot reach to code.
from discord.ext import commands
if __name__ == "__main__":
bot = commands.Bot()
bot.run(token) # blocked
try:
while(True):
sleep(1)
except KeyboardInterrupt:
session.close()
- Close session when bot is disconnected.
on_disconnect
had been not called when keyboard interrupt.
@bot.event
async def on_disconnect():
await session.close()
- edit: I missed
await
beforesession.close()
, but this was just my mistake when I wrote this question. All I tried also didn't work well as i expected when i wrote correctly withawait
.