Skip to content

Commit

Permalink
Error Management
Browse files Browse the repository at this point in the history
  • Loading branch information
fp12 committed Jan 11, 2017
1 parent 522c32c commit 5823b21
Show file tree
Hide file tree
Showing 12 changed files with 138 additions and 104 deletions.
20 changes: 16 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# achallonge
*Async Challonge for Python 3.5+*
*async Challonge for Python 3.5+*

[![Build Status](https://travis-ci.org/fp12/achallonge.svg?branch=master)](https://travis-ci.org/fp12/achallonge)
[![Documentation Status](https://readthedocs.org/projects/achallonge/badge/?version=latest)](http://achallonge.readthedocs.io/en/latest/?badge=latest)
Expand Down Expand Up @@ -39,11 +39,23 @@ async def pychallonge_async()

# Tournaments, matches, and participants are all represented as Python classes
for t in tournaments:
print(t.id) # 3272
print(t.name) # My Awesome Tournament
print(t.status) # open
print(t.id) # 3272
print(t.name) # 'My Awesome Tournament'
print(t.status) # 'open'

# Retrieve the participants for a given tournament.
participants = await tournaments[0].get_participants()
print(len(participants)) # 13
```

# Documentation

The full documentation can be found on [Read the docs](http://achallonge.readthedocs.io/en/latest/index.html)

# Author / License

Distributed under MIT license. See `LICENSE` for details

Fabien Poupineau (fp12) - 2017
Twitter: [@fp12gaming](https://twitter.com/fp12gaming)
Join the [Discord Server](https://discord.gg/KSRxBav) and discuss about this lib!
3 changes: 2 additions & 1 deletion challonge/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,10 @@
CHALLONGE_AUTO_GET_PARTICIPANTS = True
CHALLONGE_AUTO_GET_MATCHES = True
CHALLONGE_USE_FIELDS_DESCRIPTORS = True
CHALLONGE_USE_EXCEPTIONS = True


from .helpers import ChallongeException
from .helpers import APIException
from .user import User, get_user
from .tournament import Tournament, TournamentType, DoubleEliminationEnding, RankingOrder, Pairing
from .participant import Participant
Expand Down
16 changes: 10 additions & 6 deletions challonge/attachment.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,8 @@
from .helpers import FieldHolder
from .helpers import FieldHolder, assert_or_raise


class Attachment(metaclass=FieldHolder):
""" representation of a Challonge match attachment """

_fields = ['id', 'match_id', 'user_id', 'description',
'url', 'original_file_name', 'created_at',
'updated_at', 'asset_file_name', 'asset_content_type',
Expand All @@ -20,7 +19,9 @@ def _refresh_from_json(self, json_def):

@staticmethod
def prepare_params(asset, url: str, description: str):
assert (asset is not None or url is not None or description is not None), 'asset:{} - url:{} - description:{}'.format(asset, url, description)
assert_or_raise(asset is not None or url is not None or description is not None,
ValueError,
'One of the following must not be None: asset, url, description')
params = {}
if asset is not None:
params.update({'asset': asset})
Expand Down Expand Up @@ -48,7 +49,8 @@ async def change_url(self, url: str, description: str = None):
description: *optional* description for your attachment
Raises:
ChallongeException
ValueError: url must not be None
APIException
"""
await self._change(url=url, description=description)
Expand All @@ -62,7 +64,8 @@ async def change_text(self, text: str):
text: content you want to add / modify (description)
Raises:
ChallongeException
ValueError: text must not be None
APIException
"""
await self._change(description=text)
Expand All @@ -82,7 +85,8 @@ async def change_file(self, file_path: str, description: str = None):
description: *optional* description for your attachment
Raises:
ChallongeException
ValueError: file_path must not be None
APIException
"""
with open(file_path, 'rb') as f:
Expand Down
28 changes: 23 additions & 5 deletions challonge/helpers.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,24 @@
import aiohttp

from . import CHALLONGE_USE_FIELDS_DESCRIPTORS
from . import CHALLONGE_USE_FIELDS_DESCRIPTORS, CHALLONGE_USE_EXCEPTIONS


DEFAULT_TIMEOUT = 30


class ChallongeException(Exception):
""" If anything goes wrong during the request to the Challonge API, this exception will be raised """
class APIException(Exception):
""" If anything goes wrong during a request to the Challonge API, this exception will be raised. """
pass


def assert_or_raise(cond, exc, msg: str = None):
if not cond:
if CHALLONGE_USE_EXCEPTIONS:
raise exc(msg)
else:
print('a silent exception `{.__name__}` has been raised `{}`'.format(exc, msg))


class FieldDescriptor:
def __init__(self, attr):
self.attr = attr
Expand Down Expand Up @@ -61,6 +69,14 @@ def __init__(self, username: str, api_key: str, timeout, loop):
self.loop = loop

async def __call__(self, method: str, uri: str, params_prefix: str =None, **params):
""" responses codes:
200 - OK
401 - Unauthorized (Invalid API key or insufficient permissions)
404 - Object not found within your account scope
406 - Requested format is not supported - request JSON or XML only
422 - Validation error(s) for create or update method
500 - Something went wrong on our end. If you continually receive this, please contact us.
"""
params = self._prepare_params(params, params_prefix)
# print(params)

Expand All @@ -72,8 +88,10 @@ async def __call__(self, method: str, uri: str, params_prefix: str =None, **para
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.json()
if response.status >= 400:
raise ChallongeException(uri, params, response.reason)
if response.status in [401, 404, 406, 422, 500]:
raise APIException(uri, params, response.reason)
if response.status != 200:
raise ValueError
return resp
return None

Expand Down
38 changes: 22 additions & 16 deletions challonge/match.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import re

from .helpers import FieldHolder
from .helpers import FieldHolder, assert_or_raise
from .participant import Participant
from .attachment import Attachment

Expand Down Expand Up @@ -56,8 +56,8 @@ def _add_attachment(self, a: Attachment):
self.attachments.append(a)

async def _report(self, scores_csv, winner=None):
if not verify_score_format(scores_csv):
raise ValueError('Bad score format')
assert_or_raise(verify_score_format(scores_csv), ValueError, 'Wrong score format')

params = {'scores_csv': scores_csv}
if winner:
params.update({'winner_id': winner})
Expand All @@ -76,7 +76,8 @@ async def report_live_scores(self, scores_csv: str):
scores_csv: Comma separated set/game scores with player 1 score first (e.g. "1-3,3-0,3-2")
Raises:
ChallongeException
ValueError: scores_csv has a wrong format
APIException
"""
await self._report(scores_csv)
Expand All @@ -91,7 +92,8 @@ async def report_winner(self, winner: Participant, scores_csv: str):
scores_csv: Comma separated set/game scores with player 1 score first (e.g. "1-3,3-0,3-2")
Raises:
ChallongeException
ValueError: scores_csv has a wrong format
APIException
"""
await self._report(scores_csv, winner._id)
Expand All @@ -105,7 +107,7 @@ async def report_tie(self, scores_csv: str):
scores_csv: Comma separated set/game scores with player 1 score first (e.g. "1-3,3-0,3-2")
Raises:
ChallongeException
APIException
"""
await self._report(scores_csv, 'tie')
Expand All @@ -124,10 +126,14 @@ async def change_votes(self, player1_votes: int = None, player2_votes: int = Non
add: if set, votes in parameters will be added instead of overriden
Raises:
ChallongeException
ValueError: one of the votes arguments must not be None
APIException
"""
assert player1_votes is not None or player2_votes is not None
assert_or_raise(player1_votes is not None or player2_votes is not None,
ValueError,
'One of the votes must not be None')

if add:
# order a fresh update of this match
res = await self.connection('GET', 'tournaments/{}/matches/{}'.format(self._tournament_id, self._id))
Expand Down Expand Up @@ -174,7 +180,8 @@ async def attach_file(self, file_path: str, description: str = None) -> Attachme
Attachment:
Raises:
ChallongeException
ValueError: file_path must not be None
APIException
"""
with open(file_path, 'rb') as f:
Expand All @@ -193,7 +200,8 @@ async def attach_url(self, url: str, description: str = None) -> Attachment:
Attachment:
Raises:
ChallongeException
ValueError: url must not be None
APIException
"""
return await self._attach(url=url, description=description)
Expand All @@ -210,7 +218,8 @@ async def attach_text(self, text: str) -> Attachment:
Attachment: newly created instance
Raises:
ChallongeException
ValueError: text must not be None
APIException
"""
return await self._attach(description=text)
Expand All @@ -221,15 +230,12 @@ async def destroy_attachment(self, a: Attachment):
|methcoro|
Args:
a: the attachment your want to destroy
a: the attachment you want to destroy
Raises:
ChallongeException
APIException
"""
await self.connection('DELETE', 'tournaments/{}/matches/{}/attachments/{}'.format(self._tournament_id, self._id, a._id))
if a in self.attachments:
self.attachments.remove(a)
else:
# TODO: error management
pass
14 changes: 7 additions & 7 deletions challonge/participant.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@ async def change_display_name(self, new_name: str):
new_name: as described
Raises:
ChallongeException
APIException
"""
await self._change(name=new_name)
Expand All @@ -55,7 +55,7 @@ async def change_username(self, username: str):
username: Challonge username
Raises:
ChallongeException
APIException
"""
await self._change(challonge_username=username)
Expand All @@ -73,7 +73,7 @@ async def change_email(self, email: str):
email: as described
Raises:
ChallongeException
APIException
"""
await self._change(email=email)
Expand All @@ -93,7 +93,7 @@ async def change_seed(self, new_seed: int) -> int:
the same seed number as passed or `None` if something failed
Raises:
ChallongeException
APIException
"""
await self._change(seed=new_seed)
Expand All @@ -109,7 +109,7 @@ async def change_misc(self, misc: str) -> str:
misc: str content
Raises:
ChallongeException
APIException
"""
await self._change(misc=misc)
Expand All @@ -123,7 +123,7 @@ async def check_in(self):
|unstable|
Raises:
ChallongeException
APIException
"""
res = await self.connection('POST', 'tournaments/{}/participants/{}/check_in'.format(self._tournament_id, self._id))
Expand All @@ -137,7 +137,7 @@ async def undo_check_in(self):
|unstable|
Raises:
ChallongeException
APIException
"""
res = await self.connection('POST', 'tournaments/{}/participants/{}/undo_check_in'.format(self._tournament_id, self._id))
Expand Down

0 comments on commit 5823b21

Please sign in to comment.