Skip to content

Commit

Permalink
Refactor and pull out common code
Browse files Browse the repository at this point in the history
  • Loading branch information
cwendt94 committed Apr 11, 2020
1 parent 3e531ff commit c989d90
Show file tree
Hide file tree
Showing 23 changed files with 24,352 additions and 848,509 deletions.
88 changes: 88 additions & 0 deletions espn_api/base_league.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
from abc import ABC
from typing import List, Tuple

from .base_settings import BaseSettings
from .utils.logger import Logger
from .requests.espn_requests import EspnFantasyRequests

class BaseLeague(ABC):
'''Creates a League instance for Public/Private ESPN league'''
def __init__(self, league_id: int, year: int, sport: str, espn_s2=None, swid=None, username=None, password=None, debug=False):
self.logger = Logger(name=f'{sport} league', debug=debug)
self.league_id = league_id
self.year = year
self.teams = []
self.draft = []
self.player_map = {}

cookies = None
if espn_s2 and swid:
cookies = {
'espn_s2': espn_s2,
'SWID': swid
}
self.espn_request = EspnFantasyRequests(sport=sport, year=year, league_id=league_id, cookies=cookies, logger=self.logger)
if username and password:
self.espn_request.authentication(username, password)

def __repr__(self):
return 'League(%s, %s)' % (self.league_id, self.year, )

def _fetch_league(self, SettingsClass = BaseSettings):
data = self.espn_request.get_league()

self.currentMatchupPeriod = data['status']['currentMatchupPeriod']
self.scoringPeriodId = data['scoringPeriodId']
self.firstScoringPeriod = data['status']['firstScoringPeriod']
if self.year < 2018:
self.current_week = data['scoringPeriodId']
else:
self.current_week = self.scoringPeriodId if self.scoringPeriodId <= data['status']['finalScoringPeriod'] else data['status']['finalScoringPeriod']
self.settings = SettingsClass(data['settings'])
return data

def _fetch_teams(self, data, TeamClass):
'''Fetch teams in league'''
teams = data['teams']
members = data['members']
schedule = data['schedule']

team_roster = {}
for team in data['teams']:
team_roster[team['id']] = team['roster']

for team in teams:
for member in members:
# For league that is not full the team will not have a owner field
if 'owners' not in team or not team['owners']:
member = None
break
elif member['id'] == team['owners'][0]:
break
roster = team_roster[team['id']]
self.teams.append(TeamClass(team, roster=roster, member=member, schedule=schedule))

# sort by team ID
self.teams = sorted(self.teams, key=lambda x: x.team_id, reverse=False)

def _fetch_players(self):
data = self.espn_request.get_pro_players()
# Map all player id's to player name
for player in data:
self.player_map[player['id']] = player['fullName']

def _get_pro_schedule(self, scoringPeriodId: int = None):
data = self.espn_request.get_pro_schedule()

pro_teams = data['settings']['proTeams']
pro_team_schedule = {}

for team in pro_teams:
if team['id'] != 0 and str(scoringPeriodId) in team['proGamesByScoringPeriod'].keys():
game_data = team['proGamesByScoringPeriod'][str(scoringPeriodId)][0]
pro_team_schedule[team['id']] = (game_data['homeProTeamId'], game_data['date']) if team['id'] == game_data['awayProTeamId'] else (game_data['awayProTeamId'], game_data['date'])
return pro_team_schedule

def standings(self) -> List:
standings = sorted(self.teams, key=lambda x: x.final_standing if x.final_standing != 0 else x.standing, reverse=False)
return standings
4 changes: 2 additions & 2 deletions espn_api/football/settings.py → espn_api/base_settings.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
class Settings(object):
class BaseSettings(object):
'''Creates Settings object'''
def __init__(self, data):
self.reg_season_count = data['scheduleSettings']['matchupPeriodCount']
Expand All @@ -14,4 +14,4 @@ def __init__(self, data):
self.playoff_seed_tie_rule = data['scoringSettings']['playoffMatchupTieRule']

def __repr__(self):
return 'Settings(%s)' % (self.name)
return 'Settings(%s)' % (self.name)
76 changes: 6 additions & 70 deletions espn_api/basketball/league.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,73 +4,30 @@
from typing import List, Tuple
import pdb

from ..utils.logger import Logger
from ..requests.espn_requests import EspnFantasyRequests
from ..base_league import BaseLeague
from .team import Team
from .player import Player
from .matchup import Matchup
from .constant import PRO_TEAM_MAP

class League(object):
class League(BaseLeague):
'''Creates a League instance for Public/Private ESPN league'''
def __init__(self, league_id: int, year: int, espn_s2=None, swid=None, username=None, password=None, debug=False):
self.logger = Logger(name='Basketball League', debug=debug)
self.league_id = league_id
self.year = year
self.teams = []
cookies = None

if espn_s2 and swid:
cookies = {
'espn_s2': espn_s2,
'SWID': swid
}
self.espn_request = EspnFantasyRequests(sport='nba', year=year, league_id=league_id, cookies=cookies, logger=self.logger)
if username and password:
self.espn_request.authentication(username, password)
super().__init__(league_id=league_id, year=year, sport='nba', espn_s2=espn_s2, swid=swid, username=username, password=password, debug=debug)

data = self._fetch_league()
self._fetch_teams(data)

def __repr__(self):
return 'League(%s, %s)' % (self.league_id, self.year, )

def _fetch_league(self):

params = {
'view': ['mTeam', 'mRoster', 'mMatchup',]
}
data = self.espn_request.league_get(params=params)

self.currentMatchupPeriod = data['status']['currentMatchupPeriod']
self.scoringPeriodId = data['scoringPeriodId']
self.firstScoringPeriod = data['status']['firstScoringPeriod']
self.start_date = datetime.datetime.fromtimestamp(min([i[1][1]/1000 for i in self._get_nba_schedule(1).items()])).date()
data = super()._fetch_league()
self.start_date = datetime.datetime.fromtimestamp(min([i[1][1]/1000 for i in self._get_pro_schedule(1).items()])).date()

return(data)


def _fetch_teams(self, data):
'''Fetch teams in league'''
teams = data['teams']
members = data['members']
schedule = data['schedule']

team_roster = {}
for team in data['teams']:

team_roster[team['id']] = team['roster']

for team in teams:
for member in members:
# For league that is not full the team will not have a owner field
if 'owners' not in team or not team['owners']:
member = None
break
elif member['id'] == team['owners'][0]:
break
roster = team_roster[team['id']]
self.teams.append(Team(team, member, roster, schedule))
super()._fetch_teams(data, TeamClass=Team)

# replace opponentIds in schedule with team instances
for team in self.teams:
Expand All @@ -82,8 +39,6 @@ def _fetch_teams(self, data):
matchup.home_team = opponent


# sort by team ID
self.teams = sorted(self.teams, key=lambda x: x.team_id, reverse=False)

def standings(self) -> List[Team]:
standings = sorted(self.teams, key=lambda x: x.final_standing if x.final_standing != 0 else x.standing, reverse=False)
Expand All @@ -110,22 +65,3 @@ def scoreboard(self, matchupPeriod: int = None) -> List[Matchup]:

return matchups


def _get_nba_schedule(self, scoringPeriodId: int = None):
'''get nba schedule for a given scoring period'''
if not scoringPeriodId:
scoringPeriodId=self.scoringPeriodId
params = {
'view': 'proTeamSchedules_wl'
}
data = self.espn_request.get(params=params)

pro_teams = data['settings']['proTeams']
pro_team_schedule = {}

for team in pro_teams:
if team['id'] != 0 and str(scoringPeriodId) in team['proGamesByScoringPeriod'].keys():
game_data = team['proGamesByScoringPeriod'][str(scoringPeriodId)][0]
pro_team_schedule[PRO_TEAM_MAP[team['id']]] = (PRO_TEAM_MAP[game_data['homeProTeamId']], game_data['date']) if team['id'] == game_data['awayProTeamId'] else (PRO_TEAM_MAP[game_data['awayProTeamId']], game_data['date'])
return pro_team_schedule

2 changes: 0 additions & 2 deletions espn_api/football/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
__all__ = ['League',
'Team',
'Settings',
'Matchup',
'Player',
'Pick',
Expand All @@ -9,7 +8,6 @@

from .league import League
from .team import Team
from .settings import Settings
from .matchup import Matchup
from .player import Player
from .pick import Pick
Expand Down
Loading

0 comments on commit c989d90

Please sign in to comment.