Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

2018 Fantasy Football API Update #615

Merged
merged 17 commits into from
Jan 7, 2025
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions espn_api/base_league.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,6 @@ def __repr__(self):

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']
Expand All @@ -49,7 +48,6 @@ def _fetch_league(self, SettingsClass = BaseSettings):
def _fetch_draft(self):
'''Creates list of Pick objects from the leagues draft'''
data = self.espn_request.get_league_draft()

# League has not drafted yet
if not data.get('draftDetail', {}).get('drafted'):
return
Expand Down
54 changes: 46 additions & 8 deletions espn_api/requests/espn_requests.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,49 @@ class ESPNUnknownError(Exception):
pass


def checkRequestStatus(status: int, cookies=None, league_id=None) -> None:
def checkRequestStatus(status: int, cookies=None, league_id=None, league_endpoint=None, year=None, extend="", params=None, headers=None) -> tuple:
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

To make this function a little simpler, I think moving this inside the request class so then you won't have to pass all these fields to it. You then can access all of them through this.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes I was actually considering that last night, but wasn't sure if you had a reason it was defined outside the class. Moving it inside would definitely simplify access to those params for sure.

Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah no issues moving it in!

if cookies is None:
cookies = {}
if league_id is None:
league_id = ""
league_id = ""
if status == 401:
raise ESPNAccessDenied(f"League {league_id} cannot be accessed with espn_s2={cookies.get('espn_s2')} and swid={cookies.get('SWID')}")
if league_endpoint and year:
# If the current LEAGUE_ENDPOINT was using the /leagueHistory/ endpoint
if "/leagueHistory/" in league_endpoint:
alternate_endpoint = league_endpoint.replace(
"/leagueHistory/",
f"/seasons/{year}/segments/0/leagues/"
)
else:
# Switch to the /leagueHistory/{league_id}?seasonId={year} endpoint
base_endpoint = league_endpoint.replace(
f"/seasons/{year}/segments/0/leagues/",
"/leagueHistory/"
)
alternate_endpoint = f"{base_endpoint}?seasonId={year}"

endpoint = alternate_endpoint + extend
#try alternate endpoint
r = requests.get(endpoint, params=params, headers=headers, cookies=cookies)

if r.status_code == 200:
# Return the updated league endpoint if alternate works & the response
return alternate_endpoint, r.json()
else:
# If alternate fails, raise the corresponding error
raise ESPNAccessDenied(f"League {league_id} cannot be accessed with espn_s2={cookies.get('espn_s2')} and swid={cookies.get('SWID')}")
else:
# If no league endpoint or year info provided, raise the error directly
raise ESPNAccessDenied(f"League {league_id} cannot be accessed with espn_s2={cookies.get('espn_s2')} and swid={cookies.get('SWID')}")

elif status == 404:
raise ESPNInvalidLeague(f"League {league_id} does not exist")

elif status != 200:
raise ESPNUnknownError(f"ESPN returned an HTTP {status}")

# If no issues with the status code, return None, None (unchanged endpoint)
return None, None


class EspnFantasyRequests(object):
Expand All @@ -48,15 +78,23 @@ def __init__(self, sport: str, year: int, league_id: int, cookies: dict = None,
self.LEAGUE_ENDPOINT += "/leagueHistory/" + str(league_id) + "?seasonId=" + str(year)
else:
self.LEAGUE_ENDPOINT += "/seasons/" + str(year) + "/segments/0/leagues/" + str(league_id)

def league_get(self, params: dict = None, headers: dict = None, extend: str = ''):
endpoint = self.LEAGUE_ENDPOINT + extend
r = requests.get(endpoint, params=params, headers=headers, cookies=self.cookies)
checkRequestStatus(r.status_code, cookies=self.cookies, league_id=self.league_id)
alternate_endpoint, alternate_response = checkRequestStatus(r.status_code, cookies=self.cookies, league_id=self.league_id, league_endpoint=self.LEAGUE_ENDPOINT, year=self.year, extend=extend, params=params, headers=headers)

if alternate_endpoint:
self.LEAGUE_ENDPOINT = alternate_endpoint
endpoint = alternate_endpoint + extend
response = alternate_response
else:
response = r.json()

if self.logger:
self.logger.log_request(endpoint=endpoint, params=params, headers=headers, response=r.json())
return r.json() if self.year > 2017 else r.json()[0]
self.logger.log_request(endpoint=endpoint, params=params, headers=headers, response=response)

return response[0] if isinstance(response, list) else response

def get(self, params: dict = None, headers: dict = None, extend: str = ''):
endpoint = self.ENDPOINT + extend
Expand All @@ -73,7 +111,7 @@ def get_league(self):
'view': ['mTeam', 'mRoster', 'mMatchup', 'mSettings', 'mStandings']
}
data = self.league_get(params=params)
return data
return data

def get_pro_schedule(self):
'''Gets the current sports professional team schedules'''
Expand Down
Loading