separate session for every request
This commit is contained in:
parent
e0b111d7a9
commit
211d08bd84
1
bot.py
1
bot.py
@ -19,7 +19,6 @@ logging.basicConfig()
|
|||||||
|
|
||||||
bot = lib.MineBot(command_prefix='!')
|
bot = lib.MineBot(command_prefix='!')
|
||||||
hn = heavynode.Client(HEAVYNODE_TOKEN)
|
hn = heavynode.Client(HEAVYNODE_TOKEN)
|
||||||
bot.add_cleanup(hn.shutdown)
|
|
||||||
|
|
||||||
|
|
||||||
async def is_admin(ctx):
|
async def is_admin(ctx):
|
||||||
|
26
heavynode.py
26
heavynode.py
@ -13,7 +13,6 @@ class HttpError(Exception):
|
|||||||
class Client:
|
class Client:
|
||||||
def __init__(self, token):
|
def __init__(self, token):
|
||||||
self.token = token
|
self.token = token
|
||||||
self.session = aiohttp.ClientSession()
|
|
||||||
self.baseurl = 'https://control.heavynode.com/api'
|
self.baseurl = 'https://control.heavynode.com/api'
|
||||||
# global state is icky, but it sure is convenient
|
# global state is icky, but it sure is convenient
|
||||||
loop = asyncio.get_event_loop()
|
loop = asyncio.get_event_loop()
|
||||||
@ -35,15 +34,18 @@ class Client:
|
|||||||
path = '/' + path
|
path = '/' + path
|
||||||
url = self.baseurl + path
|
url = self.baseurl + path
|
||||||
|
|
||||||
r = await self.session.request(method, url, *args, **kwargs)
|
# use context managers so connection is properly closed after request
|
||||||
if r.status >= 400:
|
# we don't make many requests so this is reasonable
|
||||||
raise HttpError(f'Request failed with status code {r.status}', r)
|
async with aiohttp.ClientSession() as session:
|
||||||
elif r.status == 204:
|
async with session.request(method, url, *args, **kwargs) as r:
|
||||||
return None # no content
|
if r.status >= 400:
|
||||||
elif r.headers['Content-Type'].lower() in {'application/json', 'application/vnd.pterodactyl.v1+json'}:
|
raise HttpError(f'Request failed with status code {r.status}', r)
|
||||||
return await r.json()
|
elif r.status == 204:
|
||||||
else:
|
return None # no content
|
||||||
return await r.text
|
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):
|
async def send_command(self, cmd):
|
||||||
"""Send console command to minecraft server."""
|
"""Send console command to minecraft server."""
|
||||||
@ -56,7 +58,3 @@ class Client:
|
|||||||
Assume there's only one."""
|
Assume there's only one."""
|
||||||
r = await self.make_request('GET', '/client')
|
r = await self.make_request('GET', '/client')
|
||||||
self.server = r['data'][0]['attributes']
|
self.server = r['data'][0]['attributes']
|
||||||
|
|
||||||
async def shutdown(self):
|
|
||||||
"""Gracefully terminate HTTP session for shutdown."""
|
|
||||||
await self.session.close()
|
|
||||||
|
Loading…
x
Reference in New Issue
Block a user