Skip to content

Commit

Permalink
apply live scores to players
Browse files Browse the repository at this point in the history
  • Loading branch information
johnmadden86 committed Oct 19, 2019
1 parent 1948173 commit b60c788
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 15 deletions.
31 changes: 20 additions & 11 deletions fpl/fpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -216,14 +216,15 @@ async def get_player_summaries(self, player_ids, return_json=False):
return [PlayerSummary(player_summary)
for player_summary in player_summaries]

async def get_player(self, player_id, players=None, include_summary=False,
async def get_player(self, player_id, players=None, gameweek=None, include_summary=False,
return_json=False):
"""Returns the player with the given ``player_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/element-summary/1/ (optional)
:param gameweek: the current gameweek data (for applying live scores)
:param player_id: A player's ID.
:type player_id: string or int
:param list players: (optional) A list of players.
Expand All @@ -249,12 +250,15 @@ async def get_player(self, player_id, players=None, include_summary=False,
player["id"], return_json=True)
player.update(player_summary)

if gameweek:
player["live_score"] = gameweek.elements[player_id]["stats"]["total_points"]

if return_json:
return player

return Player(player, self.session)

async def get_players(self, player_ids=None, include_summary=False,
async def get_players(self, player_ids=None, include_summary=False, include_live=None,
return_json=False):
"""Returns either a list of *all* players, or a list of players whose
IDs are in the given ``player_ids`` list.
Expand All @@ -263,6 +267,7 @@ async def get_players(self, player_ids=None, include_summary=False,
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/element-summary/1/ (optional)
:param include_live: (optional) include a player's live score
:param list player_ids: (optional) A list of player IDs
:param boolean include_summary: (optional) Includes a player's summary
if ``True``.
Expand All @@ -273,13 +278,17 @@ async def get_players(self, player_ids=None, include_summary=False,
:rtype: list
"""
players = getattr(self, "elements")
gameweek = None

if not player_ids:
player_ids = [player["id"] for player in players.values()]

if include_live:
gameweek = await self.get_gameweek(getattr(self, "current_gameweek"), include_live=True)

tasks = [asyncio.ensure_future(
self.get_player(
player_id, players, include_summary, return_json))
player_id, players, gameweek, include_summary, return_json))
for player_id in player_ids]
players = await asyncio.gather(*tasks)

Expand Down Expand Up @@ -415,15 +424,15 @@ async def get_fixtures(self, return_json=False):

return {fixture["id"]: Fixture(fixture) for fixture in fixtures}

async def get_gameweek(self, gameweek_id, return_json=False):
async def get_gameweek(self, gameweek_id, include_live=False, return_json=False):
"""Returns the gameweek with the ID ``gameweek_id``.
Information is taken from e.g.:
https://fantasy.premierleague.com/api/bootstrap-static/
https://fantasy.premierleague.com/api/event/1/live/
:param int gameweek_id: A gameweek's ID.
:param bool include_summary: (optional) Includes a gameweek's live data
:param bool include_live: (optional) Includes a gameweek's live data
if ``True``.
:param return_json: (optional) Boolean. If ``True`` returns a ``dict``,
if ``False`` returns a :class:`Gameweek` object. Defaults to
Expand All @@ -450,16 +459,16 @@ async def get_gameweek(self, gameweek_id, return_json=False):
# include live bonus points
if not static_gameweek['finished']:
fixtures = await self.get_fixtures_by_gameweek(gameweek_id)
fixtures = filter(lambda f: not f.finished, fixtures)
fixtures = filter(lambda f: not f.finished, fixtures.values())
bonus_for_gameweek = []
for fixture in fixtures:
bonus = fixture.get_bonus(provisional=True)
bonus_for_gameweek.extend(bonus['a'] + bonus['h'])
bonus_for_gameweek = {b['element']: b['value'] for b in bonus_for_gameweek}
for player_id, bonus_points in bonus_for_gameweek:
if live_gameweek["elements"][player_id]["bonus"] == 0:
live_gameweek["elements"][player_id]["bonus"] += bonus_points
live_gameweek["elements"][player_id]["total_points"] += bonus_points
for player_id, bonus_points in bonus_for_gameweek.items():
if live_gameweek["elements"][player_id]["stats"]["bonus"] == 0:
live_gameweek["elements"][player_id]["stats"]["bonus"] += bonus_points
live_gameweek["elements"][player_id]["stats"]["total_points"] += bonus_points

static_gameweek.update(live_gameweek)

Expand Down Expand Up @@ -488,7 +497,7 @@ async def get_gameweeks(self, gameweek_ids=None, return_json=False):
gameweek_ids = range(1, 39)

tasks = [asyncio.ensure_future(
self.get_gameweek(gameweek_id, return_json))
self.get_gameweek(gameweek_id, False, return_json))
for gameweek_id in gameweek_ids]

gameweeks = await asyncio.gather(*tasks)
Expand Down
11 changes: 7 additions & 4 deletions tests/test_fpl.py
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,10 @@ async def test_players(self, loop, fpl):
summary_keys = ("history_past", "history", "fixtures")
assert all([isinstance(getattr(players[2], key), list) for key in summary_keys])

players = await fpl.get_players([1, 2, 3], include_live=True)
assert len(players.values()) == 3
assert isinstance(getattr(players[2], "live_score"), int)

players = await fpl.get_players([1, 2, 3], include_summary=True, return_json=True)
assert len(players) == 3
assert all([isinstance(players[2][key], list) for key in summary_keys])
Expand Down Expand Up @@ -222,7 +226,6 @@ async def test_gameweek(self, loop, fpl):
assert "elements" in gameweek.keys()
assert isinstance(gameweek["elements"], dict)

@pytest.mark.skip(reason="Cannot currently test it.")
async def test_classic_league(self, loop, fpl):
await fpl.login()
classic_league = await fpl.get_classic_league(173226)
Expand Down Expand Up @@ -276,11 +279,11 @@ async def test_points_against(self, loop, fpl):

# noinspection PyPep8Naming
async def test_FDR(self, loop, fpl):
def test_main(fdr):
assert isinstance(fdr, dict)
def test_main(fdr_):
assert isinstance(fdr_, dict)

location_extrema = {"H": [], "A": []}
for _, positions in fdr.items():
for _, positions in fdr_.items():
for location in positions.values():
location_extrema["H"].append(location["H"])
location_extrema["A"].append(location["A"])
Expand Down

0 comments on commit b60c788

Please sign in to comment.