from flaskapp.config import secret from flask import session, g from dateutil import parser import requests def get_toornament(code: str = None, force_new: bool = False): if code: data = { 'grant_type': 'authorization_code', 'client_id': secret['oauth_client_id'], 'client_secret': secret['oauth_client_secret'], 'redirect_uri': secret['oauth_redirect_uri'], 'code': code } request = requests.post('https://api.toornament.com/oauth/v2/token', data=data) session['access_token'] = request.json()['access_token'] if 'toornament' not in g or force_new: if session.get('access_token'): g.toornament = Toornament(secret['toornament_api_key'], session.get('access_token')) else: g.toornament = Toornament(secret['toornament_api_key']) return g.toornament class Toornament: def __init__(self, api_key: str, access_token: str = None): self.auth_header = dict() self.auth_header['X-Api-Key'] = api_key if access_token: self.auth_header['Authorization'] = 'Bearer ' + access_token def get_user_data(self) -> dict: request = requests.get( 'https://api.toornament.com/account/v2/me/info', headers=self.auth_header ) return request.json() def get_participation_data(self) -> dict: headers = { 'Range': 'participants=0-49', **self.auth_header } request = requests.get( 'https://api.toornament.com/participant/v2/me/participants', headers=headers ) return request.json() def get_participant(self, tournament_id: int, id: int) -> dict: request = requests.get( f'https://api.toornament.com/viewer/v2/tournaments/{tournament_id}/participants/{id}', headers=self.auth_header ) return request.json() def get_tournament(self, id: str) -> dict: request = requests.get( f'https://api.toornament.com/viewer/v2/tournaments/{id}', headers=self.auth_header ) return request.json() def get_matches(self, tournament_id: int, participant_id: int = None) -> dict: headers = { 'Range': 'matches=0-49', **self.auth_header } params = dict() if participant_id: # TODO: allow multiple participant_ids params['participant_ids'] = participant_id request = requests.get( f'https://api.toornament.com/viewer/v2/tournaments/{tournament_id}/matches', headers=headers, params=params ) matches = request.json() for idx, match in enumerate(matches): if match['scheduled_datetime']: matches[idx]['scheduled_datetime'] = parser.isoparse(match['scheduled_datetime']) if match['played_at']: matches[idx]['played_at'] = parser.isoparse(match['played_at']) return matches def get_match(self, tournament_id: int, id: int) -> dict: request = requests.get( f'https://api.toornament.com/viewer/v2/tournaments/{tournament_id}/matches/{id}', headers=self.auth_header ) match = request.json() if match['scheduled_datetime']: match['scheduled_datetime'] = parser.isoparse(match['scheduled_datetime']) if match['played_at']: match['played_at'] = parser.isoparse(match['played_at']) return match