Skip to content

Commit

Permalink
Fixed "Unclosed client session" and "coroutine 'Bot._api_call' was ne…
Browse files Browse the repository at this point in the history
…ver awaited" warnings
  • Loading branch information
mon4ter authored and szastupov committed Mar 10, 2018
1 parent 6b582df commit 023d9d9
Showing 1 changed file with 18 additions and 4 deletions.
22 changes: 18 additions & 4 deletions aiotg/bot.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@
"message", "edited_message", "channel_post", "edited_channel_post"
]

AIOHTTP_23 = aiohttp.__version__ > '2.3'

logger = logging.getLogger("aiotg")


Expand Down Expand Up @@ -126,22 +128,28 @@ def run(self, debug=False, reload=None):
if reload is None:
reload = debug

bot_loop = asyncio.ensure_future(self.loop())

try:
if reload:
loop.run_until_complete(
run_with_reloader(loop, self.loop(), self.stop)
run_with_reloader(loop, bot_loop, self.stop)
)

else:
loop.run_until_complete(self.loop())
loop.run_until_complete(bot_loop)

# User cancels
except KeyboardInterrupt:
logger.debug("User cancelled")
bot_loop.cancel()
self.stop()

# Stop loop
finally:
if AIOHTTP_23:
loop.run_until_complete(self.session.close())

logger.debug("Closing loop")
loop.stop()
loop.close()
Expand All @@ -164,7 +172,13 @@ def run_webhook(self, webhook_url, **options):
app = self.create_webhook_app(url.path, loop)
host = os.environ.get('HOST', '0.0.0.0')
port = int(os.environ.get('PORT', 0)) or url.port

if AIOHTTP_23:
app.on_cleanup.append(lambda _: self.session.close())

web.run_app(app, host=host, port=port)
else:
loop.run_until_complete(self.session.close())

def stop_webhook(self):
"""
Expand Down Expand Up @@ -507,15 +521,15 @@ def delete_webhook(self):

@property
def session(self):
if not self._session:
if not self._session or self._session.closed:
self._session = aiohttp.ClientSession(
json_serialize=self.json_serialize
)
return self._session

def __del__(self):
try:
if self._session:
if not AIOHTTP_23 and self._session:
self._session.close()
except Exception as e:
logger.debug(e)
Expand Down

0 comments on commit 023d9d9

Please sign in to comment.