separate session for every request

This commit is contained in:
Joseph Montanaro 2020-07-26 15:49:36 -07:00
parent e0b111d7a9
commit 211d08bd84
2 changed files with 12 additions and 15 deletions

1
bot.py
View File

@ -19,7 +19,6 @@ logging.basicConfig()
bot = lib.MineBot(command_prefix='!')
hn = heavynode.Client(HEAVYNODE_TOKEN)
bot.add_cleanup(hn.shutdown)
async def is_admin(ctx):

View File

@ -13,7 +13,6 @@ class HttpError(Exception):
class Client:
def __init__(self, token):
self.token = token
self.session = aiohttp.ClientSession()
self.baseurl = 'https://control.heavynode.com/api'
# global state is icky, but it sure is convenient
loop = asyncio.get_event_loop()
@ -35,15 +34,18 @@ class Client:
path = '/' + path
url = self.baseurl + path
r = await self.session.request(method, url, *args, **kwargs)
if r.status >= 400:
raise HttpError(f'Request failed with status code {r.status}', r)
elif r.status == 204:
return None # no content
elif r.headers['Content-Type'].lower() in {'application/json', 'application/vnd.pterodactyl.v1+json'}:
return await r.json()
else:
return await r.text
# use context managers so connection is properly closed after request
# we don't make many requests so this is reasonable
async with aiohttp.ClientSession() as session:
async with session.request(method, url, *args, **kwargs) as r:
if r.status >= 400:
raise HttpError(f'Request failed with status code {r.status}', r)
elif r.status == 204:
return None # no content
elif r.headers['Content-Type'].lower() in {'application/json', 'application/vnd.pterodactyl.v1+json'}:
return await r.json()
else:
return await r.text
async def send_command(self, cmd):
"""Send console command to minecraft server."""
@ -56,7 +58,3 @@ class Client:
Assume there's only one."""
r = await self.make_request('GET', '/client')
self.server = r['data'][0]['attributes']
async def shutdown(self):
"""Gracefully terminate HTTP session for shutdown."""
await self.session.close()