From f6a58f1b16eb898c4c69aace019ebf42a175bda2 Mon Sep 17 00:00:00 2001 From: Justin Hsieh <41461549+justin-hsieh@users.noreply.github.com> Date: Wed, 1 Nov 2023 10:24:32 -0700 Subject: [PATCH 1/3] Update submodule --- .gitignore | 2 +- .../espn_api/base_league.py | 27 +++++++++----- .../espn_api/football/team.py | 37 +++++++++++++------ 3 files changed, 44 insertions(+), 22 deletions(-) diff --git a/.gitignore b/.gitignore index 14af7ba..17f891f 100644 --- a/.gitignore +++ b/.gitignore @@ -107,4 +107,4 @@ venv.bak/ # Submodules .gitmodules -.vscode +.vscode \ No newline at end of file diff --git a/fantasy_app/espn_api_submodule/espn_api/base_league.py b/fantasy_app/espn_api_submodule/espn_api/base_league.py index 6476743..f93e7db 100644 --- a/fantasy_app/espn_api_submodule/espn_api/base_league.py +++ b/fantasy_app/espn_api_submodule/espn_api/base_league.py @@ -5,13 +5,16 @@ 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, debug=False): self.logger = Logger(name=f'{sport} league', debug=debug) self.league_id = league_id self.year = year self.teams = [] + self.members = [] self.draft = [] self.player_map = {} @@ -21,12 +24,13 @@ def __init__(self, league_id: int, year: int, sport: str, espn_s2=None, swid=Non 'espn_s2': espn_s2, 'SWID': swid } - self.espn_request = EspnFantasyRequests(sport=sport, year=year, league_id=league_id, cookies=cookies, logger=self.logger) + self.espn_request = EspnFantasyRequests( + sport=sport, year=year, league_id=league_id, cookies=cookies, logger=self.logger) def __repr__(self): return 'League(%s, %s)' % (self.league_id, self.year, ) - def _fetch_league(self, SettingsClass = BaseSettings): + def _fetch_league(self, SettingsClass=BaseSettings): data = self.espn_request.get_league() self.currentMatchupPeriod = data['status']['currentMatchupPeriod'] @@ -36,11 +40,13 @@ def _fetch_league(self, SettingsClass = BaseSettings): 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.current_week = self.scoringPeriodId if self.scoringPeriodId <= data[ + 'status']['finalScoringPeriod'] else data['status']['finalScoringPeriod'] self.settings = SettingsClass(data['settings']) + self.members = data.get('members', []) return data - def _fetch_teams(self, data, TeamClass, pro_schedule = None): + def _fetch_teams(self, data, TeamClass, pro_schedule=None): '''Fetch teams in league''' self.teams = [] teams = data['teams'] @@ -61,7 +67,8 @@ def _fetch_teams(self, data, TeamClass, pro_schedule = None): elif member['id'] == team['owners'][0]: break roster = team_roster[team['id']] - self.teams.append(TeamClass(team, roster=roster, member=member, schedule=schedule, year=seasonId, pro_schedule=pro_schedule)) + self.teams.append(TeamClass(team, roster=roster, member=member, + schedule=schedule, year=seasonId, pro_schedule=pro_schedule)) # sort by team ID self.teams = sorted(self.teams, key=lambda x: x.team_id, reverse=False) @@ -86,9 +93,10 @@ def _get_pro_schedule(self, scoringPeriodId: int = None): pro_game = team.get('proGamesByScoringPeriod', {}) if team['id'] != 0 and (str(scoringPeriodId) in pro_game.keys() and pro_game[str(scoringPeriodId)]): game_data = pro_game[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']) + 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 _get_all_pro_schedule(self): data = self.espn_request.get_pro_schedule() @@ -101,5 +109,6 @@ def _get_all_pro_schedule(self): 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 \ No newline at end of file + standings = sorted( + self.teams, key=lambda x: x.final_standing if x.final_standing != 0 else x.standing, reverse=False) + return standings diff --git a/fantasy_app/espn_api_submodule/espn_api/football/team.py b/fantasy_app/espn_api_submodule/espn_api/football/team.py index d09c729..4cf01ea 100644 --- a/fantasy_app/espn_api_submodule/espn_api/football/team.py +++ b/fantasy_app/espn_api_submodule/espn_api/football/team.py @@ -1,23 +1,32 @@ from .player import Player + class Team(object): '''Teams are part of the league''' + def __init__(self, data, roster, member, schedule, year, **kwargs): self.team_id = data['id'] self.team_abbrev = data['abbrev'] - self.team_name = "%s %s" % (data['location'], data['nickname']) + self.team_name = data.get('name', 'Unknown') + if self.team_name == 'Unknown': + self.team_name = "%s %s" % ( + data.get('location', 'Unknown'), data.get('nickname', 'Unknown')) self.division_id = data['divisionId'] - self.division_name = '' # set by caller + self.division_name = '' # set by caller self.wins = data['record']['overall']['wins'] self.losses = data['record']['overall']['losses'] self.ties = data['record']['overall']['ties'] self.points_for = data['record']['overall']['pointsFor'] - self.points_against = round(data['record']['overall']['pointsAgainst'], 2) - self.acquisitions = data.get('transactionCounter', {}).get('acquisitions', 0) - self.acquisition_budget_spent = data.get('transactionCounter', {}).get('acquisitionBudgetSpent', 0) + self.points_against = round( + data['record']['overall']['pointsAgainst'], 2) + self.acquisitions = data.get( + 'transactionCounter', {}).get('acquisitions', 0) + self.acquisition_budget_spent = data.get( + 'transactionCounter', {}).get('acquisitionBudgetSpent', 0) self.drops = data.get('transactionCounter', {}).get('drops', 0) self.trades = data.get('transactionCounter', {}).get('trades', 0) - self.playoff_pct = data.get('currentSimulationResults', {}).get('playoffPct', 0) * 100 + self.playoff_pct = data.get( + 'currentSimulationResults', {}).get('playoffPct', 0) * 100 self.draft_projected_rank = data.get('draftDayProjectedRank', 0) self.owner = 'None' if member: @@ -27,7 +36,7 @@ def __init__(self, data, roster, member, schedule, year, **kwargs): self.streak_type = data['record']['overall']['streakType'] self.standing = data['playoffSeed'] self.final_standing = data['rankCalculatedFinal'] - if 'logo' in data: + if 'logo' in data: self.logo_url = data['logo'] else: self.logo_url = '' @@ -37,11 +46,12 @@ def __init__(self, data, roster, member, schedule, year, **kwargs): self.outcomes = [] self.mov = [] self._fetch_schedule(schedule) + self.owners = data.get('owners', []) self._fetch_roster(roster, year) def __repr__(self): return 'Team(%s)' % (self.team_name, ) - + def _fetch_roster(self, data, year): '''Fetch teams roster''' self.roster.clear() @@ -58,22 +68,25 @@ def _fetch_schedule(self, data): if matchup['away']['teamId'] == self.team_id: score = matchup['away']['totalPoints'] opponentId = matchup['home']['teamId'] - self.outcomes.append(self._get_winner(matchup['winner'], True)) + self.outcomes.append( + self._get_winner(matchup['winner'], True)) self.scores.append(score) self.schedule.append(opponentId) elif matchup['home']['teamId'] == self.team_id: score = matchup['home']['totalPoints'] opponentId = matchup['away']['teamId'] - self.outcomes.append(self._get_winner(matchup['winner'], False)) + self.outcomes.append( + self._get_winner(matchup['winner'], False)) self.scores.append(score) self.schedule.append(opponentId) elif matchup['home']['teamId'] == self.team_id: score = matchup['home']['totalPoints'] opponentId = matchup['home']['teamId'] - self.outcomes.append(self._get_winner(matchup['winner'], False)) + self.outcomes.append( + self._get_winner(matchup['winner'], False)) self.scores.append(score) self.schedule.append(opponentId) - + def _get_winner(self, winner: str, is_away: bool) -> str: if winner == 'UNDECIDED': return 'U' From 65d203f764a32c839d7d899db8290cc0a641775d Mon Sep 17 00:00:00 2001 From: Justin Hsieh <41461549+justin-hsieh@users.noreply.github.com> Date: Wed, 1 Nov 2023 10:29:22 -0700 Subject: [PATCH 2/3] Update key.json --- key.json | 14 +------------- 1 file changed, 1 insertion(+), 13 deletions(-) diff --git a/key.json b/key.json index 79b1826..8b13789 100644 --- a/key.json +++ b/key.json @@ -1,13 +1 @@ -{ - "type": "service_account", - "project_id": "fantasy-contests", - "private_key_id": "666c2a25326a1a0d4026e850e881eb9f399ab6fc", - "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCulw7bps+GQB3w\n4GS130M0YwNi0YgI2gvZ/JZy1HrweSgP9ZCaiKNgEgRZPvhhMfol+qEirEpnI6Z6\nfT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lJITrrpK0JuV8030IC9INsKkn\nwPeRYrw8UM61pcsWWUjd6yH/bRNAlPctWC+CYz73NZtwFeP16Hg8noxxAoGABsRH\nBJuby+h5q4E3/39ldmtfWwdAaX1PI04cK6gIcDJGPrz7wCrxT37f8Bh3NhbvnEYb\nq2EY2IjN+w//3nnh4B5KvZkfRz3OftU8LATisW/Fv7yFJEwoC2skrjYAzIYJWpNr\n3W8/dJFuYdZFyg7SaBnUSL9CL7yB98BTd/k+GYMCgYBdsdPTW+Cwnnhcx7zh4A/E\nn6F3g1Iny9qjx+OnKFL2Q+gU4Wr1GYbSL5rwBFIED2cXNcBXnPtTsdJxN8iqxHB3\nkNpqw9SdJR2qverh1AlRbjBY2KgiCM5VqrhBUBWhiEXZ+LTAoW1gfTK9sWxY8yEI\nd9Tg26imYxeYfM4O8WwQFg==\n-----END PRIVATE KEY-----\n", - "client_email": "firebase-adminsdk-atqc1@fantasy-contests.iam.gserviceaccount.com", - "client_id": "118329157944890218182", - "auth_uri": "https://accounts.google.com/o/oauth2/auth", - "token_uri": "https://oauth2.googleapis.com/token", - "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", - "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-atqc1%40fantasy-contests.iam.gserviceaccount.com", - "universe_domain": "googleapis.com" -} + From 8d9207915314296f73a80886188c414257d516eb Mon Sep 17 00:00:00 2001 From: Justin Hsieh <41461549+justin-hsieh@users.noreply.github.com> Date: Thu, 9 Nov 2023 13:26:11 -0700 Subject: [PATCH 3/3] delete key --- db.ipynb | 174 +++++++++++++++++++++++++++++++++++++++++++++++++------ key.json | 1 - 2 files changed, 155 insertions(+), 20 deletions(-) delete mode 100644 key.json diff --git a/db.ipynb b/db.ipynb index e9ec329..7fca144 100644 --- a/db.ipynb +++ b/db.ipynb @@ -2,7 +2,7 @@ "cells": [ { "cell_type": "code", - "execution_count": 15, + "execution_count": 1, "metadata": {}, "outputs": [], "source": [ @@ -16,14 +16,38 @@ "metadata": {}, "outputs": [], "source": [ - "firebase_admin.delete_app(firebase_admin.get_app())" + "#firebase_admin.delete_app(firebase_admin.get_app())" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 53, "metadata": {}, "outputs": [], + "source": [ + "from dotenv import load_dotenv\n", + "import os\n", + "load_dotenv()\n", + "DATABASE_URL = os.getenv('DATABASE_URL')\n", + "CREDS = os.getenv('CREDS')" + ] + }, + { + "cell_type": "code", + "execution_count": 3, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 3, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "cred = credentials.Certificate(\"key.json\")\n", "firebase_admin.initialize_app(cred, {\"databaseURL\": \"https://fantasy-contests-default-rtdb.firebaseio.com/\"})" @@ -31,46 +55,82 @@ }, { "cell_type": "code", - "execution_count": 31, + "execution_count": 54, "metadata": {}, "outputs": [], "source": [ + "\n", "if not firebase_admin._apps:\n", + " cred = credentials.Certificate(CREDS)\n", " firebase_admin.initialize_app(cred, {\n", - " 'databaseURL': 'https://fantasy-contests-default-rtdb.firebaseio.com/'\n", + " 'databaseURL': DATABASE_URL\n", " })" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 5, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 5, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ "firebase_admin.get_app()" ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [] + }, { "cell_type": "code", - "execution_count": 33, + "execution_count": 8, "metadata": {}, - "outputs": [], + "outputs": [ + { + "data": { + "text/plain": [ + "" + ] + }, + "execution_count": 8, + "metadata": {}, + "output_type": "execute_result" + } + ], "source": [ - "ref = db.reference(\"/\")" + "ref.push(\"2023\")" ] }, { "cell_type": "code", - "execution_count": 35, + "execution_count": 52, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "{'name': 'JJ'}" + "{'-Nijq-obWPuF13Udi6zl': {'Week_7': {'contest': 'vnake;jrhngf',\n", + " 'contest_results': [{'players': [{'game_played': 100,\n", + " 'name': 'Roquan Smith',\n", + " 'score': 7.4},\n", + " {'game_played': 100, 'name': \"Ja'Whaun Bentley\", 'score': 31.3}],\n", + " 'rank': 1,\n", + " 'team': 'Lets Get Weird 🐸',\n", + " 'total_score': 6999}]}}}" ] }, - "execution_count": 35, + "execution_count": 52, "metadata": {}, "output_type": "execute_result" } @@ -81,31 +141,107 @@ }, { "cell_type": "code", - "execution_count": 34, + "execution_count": 36, + "metadata": {}, + "outputs": [], + "source": [ + "ref = db.reference(\"/2022\")" + ] + }, + { + "cell_type": "code", + "execution_count": 38, "metadata": {}, "outputs": [ { "data": { "text/plain": [ - "'JJ'" + "{'-Nijq-obWPuF13Udi6zl': {'Week_7': {'contest': 'fdsafsd',\n", + " 'contest_results': [{'players': [{'game_played': 100,\n", + " 'name': 'Foyesade Oluokun',\n", + " 'score': 39.1},\n", + " {'game_played': 100, 'name': 'Ernest Jones', 'score': 6.7}],\n", + " 'rank': 1,\n", + " 'team': 'Lets Get Weird 🐸',\n", + " 'total_score': 45.800000000000004}]}}}" ] }, - "execution_count": 34, + "execution_count": 38, "metadata": {}, "output_type": "execute_result" } ], "source": [ - "db.reference(\"/name\").get()" + "db.reference(\"/2022\").get()" + ] + }, + { + "cell_type": "code", + "execution_count": 28, + "metadata": {}, + "outputs": [], + "source": [ + "ref.update({\n", + " \"Week_7\":\n", + " {\n", + " \"contest\": \"vnake;jrhngf\",\n", + " \"contest_results\": [\n", + " {\n", + " \"players\": [\n", + " {\n", + " \"game_played\": 100,\n", + " \"name\": \"Roquan Smith\",\n", + " \"score\": 7.4\n", + " },\n", + " {\n", + " \"game_played\": 100,\n", + " \"name\": \"Ja'Whaun Bentley\",\n", + " \"score\": 31.3\n", + " }\n", + " ],\n", + " \"rank\": 1,\n", + " \"team\": \"Lets Get Weird \\ud83d\\udc38\",\n", + " \"total_score\": 45.800000000000004\n", + " }\n", + " ]\n", + "}\n", + "})" ] }, { "cell_type": "code", - "execution_count": null, + "execution_count": 51, "metadata": {}, "outputs": [], "source": [ - "db.reference(\"/name\").set('Justy')" + "\n", + "for key, value in ref.get().items():\n", + " if (value[\"Week_7\"]):\n", + "\n", + " ref.child(key).child(\"Week_7\").update(\n", + " {\n", + " \"contest\": \"vnake;jrhngf\",\n", + " \"contest_results\": [\n", + " {\n", + " \"players\": [\n", + " {\n", + " \"game_played\": 100,\n", + " \"name\": \"Roquan Smith\",\n", + " \"score\": 7.4\n", + " },\n", + " {\n", + " \"game_played\": 100,\n", + " \"name\": \"Ja'Whaun Bentley\",\n", + " \"score\": 31.3\n", + " }\n", + " ],\n", + " \"rank\": 1,\n", + " \"team\": \"Lets Get Weird \\ud83d\\udc38\",\n", + " \"total_score\": 6999\n", + " }\n", + " ]\n", + "}\n", + ")" ] } ], diff --git a/key.json b/key.json deleted file mode 100644 index 8b13789..0000000 --- a/key.json +++ /dev/null @@ -1 +0,0 @@ -