Skip to content

Commit

Permalink
Fix unclosed sessions
Browse files Browse the repository at this point in the history
Now it's 1 client session per request.
May be optimized later?
  • Loading branch information
fp12 committed Dec 28, 2016
1 parent 61ec989 commit 3465893
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 16 deletions.
28 changes: 12 additions & 16 deletions challonge/helpers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import asyncio
import json
import aiohttp

Expand Down Expand Up @@ -43,14 +42,11 @@ def __init__(cls, name, bases, dct):
class Connection:
challonge_api_url = 'https://api.challonge.com/v1/{}.json'

def __init__(self, username: str, api_key: str, session, timeout):
def __init__(self, username: str, api_key: str, timeout, loop):
self.username = username
self.api_key = api_key
self.session = session
self.timeout = timeout

def __del__(self):
self.session.close()
self.loop = loop

async def __call__(self, method: str, uri: str, params_prefix: str =None, **params):
params = self._prepare_params(params, params_prefix)
Expand All @@ -59,12 +55,14 @@ async def __call__(self, method: str, uri: str, params_prefix: str =None, **para
# build the HTTP request and use basic authentication
url = self.challonge_api_url.format(uri)

with aiohttp.Timeout(self.timeout):
async with self.session.request(method, url, params=params, auth=aiohttp.BasicAuth(login=self.username, password=self.api_key)) as response:
resp = await response.text()
if response.status >= 400:
raise ChallongeException(uri, params, response.reason)
return json.loads(resp)
async with aiohttp.ClientSession(loop=self.loop) as session:
with aiohttp.Timeout(self.timeout):
auth = aiohttp.BasicAuth(login=self.username, password=self.api_key)
async with session.request(method, url, params=params, auth=auth) as response:
resp = await response.text()
if response.status >= 400:
raise ChallongeException(uri, params, response.reason)
return json.loads(resp)
return None

@staticmethod
Expand All @@ -87,10 +85,8 @@ def val(value):
return new_params


def get_connection(username, api_key, loop=None, timeout=DEFAULT_TIMEOUT):
loop = loop or asyncio.get_event_loop()
session = aiohttp.ClientSession(loop=loop)
return Connection(username, api_key, session, timeout)
def get_connection(username, api_key, timeout=DEFAULT_TIMEOUT, loop=None):
return Connection(username, api_key, timeout, loop)


def get_from_dict(s, data, *args):
Expand Down
1 change: 1 addition & 0 deletions tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,7 @@ def test_d_update_participants(self):
self.assertEqual(p.seed, 2)
yield from self.user.destroy_tournament(t)

# @unittest.skip('')
@async_test
def test_e_bulk(self):
random_name = get_random_name()
Expand Down

0 comments on commit 3465893

Please sign in to comment.