Skip to content

Commit

Permalink
Refactor standings methods
Browse files Browse the repository at this point in the history
  • Loading branch information
panzarino committed Sep 8, 2017
1 parent 602ff2e commit bda8eb2
Show file tree
Hide file tree
Showing 4 changed files with 72 additions and 76 deletions.
3 changes: 2 additions & 1 deletion mlbgame/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,7 +250,8 @@ def standings(date=datetime.now()):
date should be a datetime object,
leave empty to get current standings
"""
return mlbgame.info.Standings(date)
data = mlbgame.info.standings(date)
return mlbgame.info.Standings(data)


def injury(team_id):
Expand Down
34 changes: 29 additions & 5 deletions mlbgame/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,12 @@
GAME_URL = BASE_URL + '/gid_{3}/{4}'
PROPERTY_URL = 'http://mlb.mlb.com/properties/mlb_properties.xml'
ROSTER_URL = 'http://mlb.mlb.com/lookup/json/named.roster_40.bam?team_id={0}'
STANDINGS_URL = ('http://mlb.mlb.com/lookup/json/named.standings_schedule_date.bam?season={0}&'
'schedule_game_date.game_date=%27{1}%27&sit_code=%27h0%27&league_id=103&'
'league_id=104&all_star_sw=%27N%27&version=2')
STANDINGS_HISTORICAL_URL = ('http://mlb.mlb.com/lookup/json/named.historical_standings_schedule_date.bam?season={0}&'
'game_date=%27{1}%27&sit_code=%27h0%27&league_id=103&'
'league_id=104&all_star_sw=%27N%27&version=48')
# Local Directory
PWD = os.path.join(os.path.dirname(__file__))

Expand All @@ -42,7 +48,7 @@ def get_box_score(game_id):
game_id,
'boxscore.xml'))
except HTTPError:
raise ValueError("Could not find a game with that id.")
raise ValueError('Could not find a game with that id.')


def get_game_events(game_id):
Expand All @@ -53,7 +59,7 @@ def get_game_events(game_id):
game_id,
'game_events.xml'))
except HTTPError:
raise ValueError("Could not find a game with that id.")
raise ValueError('Could not find a game with that id.')


def get_overview(game_id):
Expand All @@ -64,7 +70,7 @@ def get_overview(game_id):
game_id,
'linescore.xml'))
except HTTPError:
raise ValueError("Could not find a game with that id.")
raise ValueError('Could not find a game with that id.')


def get_players(game_id):
Expand All @@ -75,7 +81,7 @@ def get_players(game_id):
game_id,
"players.xml"))
except HTTPError:
raise ValueError("Could not find a game with that id.")
raise ValueError('Could not find a game with that id.')


def get_properties():
Expand All @@ -94,7 +100,25 @@ def get_roster(team_id):
try:
return urlopen(ROSTER_URL.format(team_id))
except HTTPError:
raise ValueError("Could not find a roster for a team with that id.")
raise ValueError('Could not find a roster for a team with that id.')


def get_standings(date):
"""Return the standings file for current standings (given current date)."""
try:
return urlopen(STANDINGS_URL.format(date.year, date.strftime('%Y/%m/%d')))
except HTTPError:
ValueError('Could not find the standings file. '
'mlb.com does not provide the file that '
'mlbgame needs to perform this operation.')


def get_historical_standings(date):
"""Return the historical standings file for specified date."""
try:
return urlopen(STANDINGS_HISTORICAL_URL.format(date.year, date.strftime('%Y/%m/%d')))
except HTTPError:
ValueError('Could not find standings for that date.')


def get_date_from_game_id(game_id):
Expand Down
109 changes: 40 additions & 69 deletions mlbgame/info.py
Original file line number Diff line number Diff line change
Expand Up @@ -203,16 +203,7 @@ class Player(mlbgame.object.Object):
pass


class Standings(object):
"""Holds information about the league standings
Properties:
standings_url
divisions
standings_json
standings_schedule_date
last_update
"""
def standings(date):
DIVISIONS = {
'AL': {
'201': 'AL East',
Expand All @@ -225,70 +216,50 @@ class Standings(object):
'203': 'NL West',
}
}

def __init__(self, date):
now = datetime.now()
if date.year == now.year and date.month == now.month and date.day == now.day:
self.standings_url = ('http://mlb.mlb.com/lookup/json/named.standings_schedule_date.bam?season=%s&'
'schedule_game_date.game_date=%%27%s%%27&sit_code=%%27h0%%27&league_id=103&'
'league_id=104&all_star_sw=%%27N%%27&version=2') % (date.year, date.strftime('%Y/%m/%d'))
self.standings_schedule_date = 'standings_schedule_date'
else:
self.standings_url = ('http://mlb.mlb.com/lookup/json/named.historical_standings_schedule_date.bam?season=%s&'
'game_date=%%27%s%%27&sit_code=%%27h0%%27&league_id=103&'
'league_id=104&all_star_sw=%%27N%%27&version=48') % (date.year, date.strftime('%Y/%m/%d'))
self.standings_schedule_date = 'historical_standings_schedule_date'
self.divisions = []
self.parse_standings()
self.last_update = self.set_last_update()

@property
def standings_json(self):
"""Return standings output as json"""
try:
return requests.get(self.standings_url).json()
except requests.exceptions.RequestException as e:
print(e)
sys.exit(-1)

def set_last_update(self):
"""Return a dateutil object from string [last update]
originally in ISO 8601 format: YYYY-mm-ddTHH:MM:SS"""
last_update = self.standings_json[self.standings_schedule_date][
now = datetime.now()
divisions = []
if date.year == now.year and date.month == now.month and date.day == now.day:
data = mlbgame.data.get_standings(date)
standings_schedule_date = 'standings_schedule_date'
else:
data = mlbgame.data.get_historical_standings(date)
standings_schedule_date = 'historical_standings_schedule_date'
parsed = json.loads(data.read().decode('utf-8'))
last_update = parsed[standings_schedule_date][
'standings_all_date_rptr']['standings_all_date'][0]['queryResults']['created']
return dateutil.parser.parse(last_update)

def parse_standings(self):
"""Parse the json standings"""
sjson = self.standings_json[self.standings_schedule_date]['standings_all_date_rptr']['standings_all_date']
for league in sjson:
if league['league_id'] == '103':
divisions = Standings.DIVISIONS['AL']
elif league['league_id'] == '104':
divisions = Standings.DIVISIONS['NL']
else:
# Raise Error
try:
raise UnknownLeagueID(
'An unknown `league_id` was passed from standings json.')
except UnknownLeagueID as e:
print('StandingsError: %s' % e)
raise
sys.exit(-1)

for division in divisions:
teams = [team for team in league['queryResults']
['row'] if team['division_id'] == division]
mlbdiv = Division(divisions[division], teams)
self.divisions.append(mlbdiv)
sjson = parsed[standings_schedule_date]['standings_all_date_rptr']['standings_all_date']
for league in sjson:
if league['league_id'] == '103':
divs = DIVISIONS['AL']
elif league['league_id'] == '104':
divs = DIVISIONS['NL']
for division in divs:
teams = [team for team in league['queryResults']
['row'] if team['division_id'] == division]
divisions.append({
'division': divs[division],
'teams': teams
})
return {
'standings_schedule_date': standings_schedule_date,
'divisions': divisions,
'last_update': dateutil.parser.parse(last_update)
}


class StandingsException(Exception):
"""Standings Exceptions"""
class Standings(object):
"""Holds information about the league standings
Properties:
divisions
standings_schedule_date
last_update
"""

class UnknownLeagueID(StandingsException):
"""An unknown `league_id` was passed from standings json"""
def __init__(self, data):
self.standings_schedule_date = data['standings_schedule_date']
self.last_update = data['last_update']
self.divisions = [Division(x['division'], x['teams']) for x in data['divisions']]


class Division(object):
Expand Down
2 changes: 1 addition & 1 deletion tests/test_info.py
Original file line number Diff line number Diff line change
Expand Up @@ -239,7 +239,7 @@ def test_roster(self):
self.assertIsInstance(player.name_use, str)
self.assertIsInstance(player.player_id, int)
self.assertIsInstance(player.position_txt, str)
self.assertIsInstance(player.primary_position, int)
self.assertIsInstance(player.primary_position, (int, str))
self.assertIsInstance(player.pro_debut_date, str)
self.assertIsInstance(player.start_date, str)
self.assertIsInstance(player.starter_sw, str)
Expand Down

0 comments on commit bda8eb2

Please sign in to comment.