Ejemplo n.º 1
0
    def all_seasons_played():
        """This method is used to get a list of all seasons played and display on the Standings index page
        for players to click through to see the season standings / points scored by player"""
        session = DbSessionFactory.create_session()

        seasons_played = (session.query(PlayerPicks.season).distinct(
            PlayerPicks.season).order_by(PlayerPicks.season.desc()))

        session.close()

        return seasons_played
Ejemplo n.º 2
0
    def find_account_by_id(cls, user_id):
        if not user_id:
            return None

        user_id = user_id.strip()

        session = DbSessionFactory.create_session()

        account = session.query(Account).filter(Account.id == user_id).first()

        return account
Ejemplo n.º 3
0
    def get_account_date(cls, user_id):
        session = DbSessionFactory.create_session()

        account_created = session.query(Account.created).first()
        account_string = str(account_created[0])
        account_date_split = account_string.split()
        account_date = account_date_split[0]

        session.close()

        return account_date
Ejemplo n.º 4
0
    def last_game_date():
        session = DbSessionFactory.create_session()

        last_game_date = session.query(SeasonInfo.season_end_date).first()
        last_game_info = str(last_game_date[0])
        last_game = pendulum.parse(last_game_info, tz=timezone)
        final_date = last_game.add(days=3)

        session.close()

        return final_date
Ejemplo n.º 5
0
    def find_account_by_email(cls, email):

        if not email or not email.strip():
            return None

        email = email.lower().strip()

        session = DbSessionFactory.create_session()

        account = session.query(Account).filter(Account.email == email).first()

        return account
Ejemplo n.º 6
0
    def get_hitter_stats():
        """Get stats for hitters (home runs, batting average and ERA) from MySportsFeeds and insert into the database"""

        session = DbSessionFactory.create_session()

        season_row = session.query(SeasonInfo).filter(
            SeasonInfo.id == "1").first()
        season = season_row.current_season

        response = requests.get(
            "https://api.mysportsfeeds.com/v2.0/pull/mlb/" + str(season) +
            "-regular/player_stats_totals.json?position=C,1B,2B,SS,3B,OF,RF,CF,LF,DH",
            auth=HTTPBasicAuth(config.msf_api, config.msf_v2pw),
        )

        player_json = response.json()
        player_data = player_json["playerStatsTotals"]

        for players in player_data:
            try:
                player_id = players["player"]["id"]
                home_runs = players["stats"]["batting"]["homeruns"]
                RBI = players["stats"]["batting"]["runsBattedIn"]
                batting_average = players["stats"]["batting"]["battingAvg"]
                at_bats = players["stats"]["batting"]["atBats"]
                hits = players["stats"]["batting"]["hits"]
                plate_appearances = players["stats"]["batting"][
                    "plateAppearances"]
                player_games_played = players["stats"]["gamesPlayed"]

            except KeyError:
                continue

            update_date = get_update_date()

            weekly_player_stats = WeeklyMLBPlayerStats(
                player_id=player_id,
                season=season,
                home_runs=home_runs,
                RBI=RBI,
                batting_average=batting_average,
                at_bats=at_bats,
                hits=hits,
                plate_appearances=plate_appearances,
                player_games_played=player_games_played,
                update_date=update_date,
            )

            session.add(weekly_player_stats)

            session.commit()

            session.close()
Ejemplo n.º 7
0
    def too_many(self):
        if not self.logged_in_user_id:
            print("Cannot view account page, you must be logged in")
            self.redirect("/account/signin")

        session = DbSessionFactory.create_session()
        season_row = (session.query(
            SeasonInfo.current_season).filter(SeasonInfo.id == "1").first())
        season = season_row.current_season

        session.close()

        return {"season": season}
Ejemplo n.º 8
0
    def set_password(cls, plain_text_password, account_id):
        print("Resetting password for user {}".format(account_id))
        session = DbSessionFactory.create_session()

        account = session.query(Account).filter(
            Account.id == account_id).first()

        if not account:
            print("Warning: Cannot reset password, no account found.")
            return

        print("New password set.")
        account.password_hash = AccountService.hash_text(plain_text_password)
        session.commit()
Ejemplo n.º 9
0
    def use_reset_code(cls, reset_code, user_ip):
        session = DbSessionFactory.create_session()

        reset = (session.query(PasswordReset).filter(
            PasswordReset.id == reset_code).first())

        if not reset:
            return

        reset.used_ip_address = user_ip
        reset.was_used = True
        reset.used_date = datetime.datetime.now()

        session.commit()
Ejemplo n.º 10
0
    def stats_already_ran(self):
        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        return {}
Ejemplo n.º 11
0
    def index(self):
        """GET request for the admin homepage.  If the database is empty, redirect to new_install"""
        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        get_first_name = (
            session.query(Account.first_name)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )
        first_name = get_first_name[0]

        season_info = session.query(SeasonInfo).all()

        if GameDayService.admin_check() is None:
            self.redirect("/admin/new_season")

        else:

            season_start_date = GameDayService.season_opener_date()
            picks_due = GameDayService.picks_due()
            time_due = GameDayService.time_due()

            # Use the string above in a Pendulum instance and get the time deltas needed
            now_time = TimeService.get_time()

            days = GameDayService.delta_days()
            hours = GameDayService.delta_hours()
            minutes = GameDayService.delta_minutes()

            return {
                "picks_due": picks_due,
                "time_due": time_due,
                "days": days,
                "hours": hours,
                "minutes": minutes,
                "first_name": first_name,
                "season_info": season_info,
            }

        session.close()
Ejemplo n.º 12
0
    def get_pitcher_stats():
        """Get cumulative Pitcher stats (wins and ERA) from MySportsFeeds and insert into the database"""

        session = DbSessionFactory.create_session()

        season_row = session.query(SeasonInfo).filter(
            SeasonInfo.id == "1").first()
        season = season_row.current_season

        response = requests.get(
            "https://api.mysportsfeeds.com/v2.0/pull/mlb/" + str(season) +
            "-regular/player_stats_totals.json?position=P",
            auth=HTTPBasicAuth(config.msf_api, config.msf_v2pw),
        )

        player_json = response.json()
        player_data = player_json["playerStatsTotals"]

        for players in player_data:
            try:
                player_id = players["player"]["id"]
                ERA = players["stats"]["pitching"]["earnedRunAvg"]
                pitcher_wins = players["stats"]["pitching"]["wins"]
                earned_runs = players["stats"]["pitching"]["earnedRunsAllowed"]
                innings_pitched = players["stats"]["pitching"][
                    "inningsPitched"]
                saves = players["stats"]["pitching"]["saves"]

            except KeyError:
                continue

            update_date = get_update_date()

            weekly_player_stats = WeeklyMLBPlayerStats(
                player_id=player_id,
                season=season,
                ERA=ERA,
                pitcher_wins=pitcher_wins,
                earned_runs=earned_runs,
                innings_pitched=innings_pitched,
                saves=saves,
                update_date=update_date,
            )

            session.add(weekly_player_stats)

            session.commit()

            session.close()
Ejemplo n.º 13
0
    def add_active_mlbplayers(
        cls,
        season: int,
        team_id: int,
        firstname: str,
        lastname: str,
        position: str,
        player_id: int,
    ):

        session = DbSessionFactory.create_session()

        season_row = session.query(SeasonInfo).filter(
            SeasonInfo.id == "1").first()
        season = season_row.current_season

        response = requests.get(
            "https://api.mysportsfeeds.com/v2.0/pull/mlb/"
            "players.json?season=" + str(season) +
            "&rosterstatus=assigned-to-roster",
            auth=HTTPBasicAuth(config.msf_api, config.msf_v2pw),
        )

        player_info = response.json()
        player_list = player_info["players"]

        for players in player_list:
            try:
                firstname = players["player"]["firstName"]
                lastname = players["player"]["lastName"]
                player_id = players["player"]["id"]
                team_id = players["player"]["currentTeam"]["id"]
                position = players["player"]["primaryPosition"]
            except TypeError:
                continue

            active_players = ActiveMLBPlayers(
                firstname=firstname,
                lastname=lastname,
                player_id=player_id,
                team_id=team_id,
                position=position,
                season=season,
            )

            session.add(active_players)

            session.commit()
            session.close()
Ejemplo n.º 14
0
def admin_check():
    """Create a check that only the user who is True in the AccountInfo database with is_superuser can access
    the admin pages.  Make sure mlbpool/data/config.py has an email assigned that matches the user during
    registration"""
    session = DbSessionFactory.create_session()
    su__query = (session.query(
        Account.id).filter(Account.is_super_user == 1).filter(
            Account.id == self.logged_in_user_id).first())
    print(su__query)

    if not su__query[0] == self.logged_in_user_id:
        print("You must be an administrator to view this page")
        self.redirect("/home")

    session.close()
Ejemplo n.º 15
0
    def completed(self):
        if not self.logged_in_user_id:
            print("Cannot view account page, you must be logged in")
            self.redirect("/account/signin")

        session = DbSessionFactory.create_session()
        season_row = (session.query(
            SeasonInfo.current_season).filter(SeasonInfo.id == "1").first())
        season = season_row.current_season

        get_first_name = (session.query(Account.first_name).filter(
            Account.id == self.logged_in_user_id).first())
        first_name = get_first_name[0]

        return {"season": season, "first_name": first_name}
Ejemplo n.º 16
0
    def create_reset_code(email):

        account = AccountService.find_account_by_email(email)
        if not account:
            return None

        session = DbSessionFactory.create_session()

        reset = PasswordReset()
        reset.used_ip_address = "1.2.3.4"  # set for real
        reset.user_id = account.id

        session.add(reset)
        session.commit()

        return reset
Ejemplo n.º 17
0
    def get_hitter_trade(
        cls,
        player_id: int,
        team_id: int,
        hr: int,
        ba: float,
        ab: int,
        hits: int,
        pa: int,
        games: int,
        rbi: int,
    ):

        session = DbSessionFactory.create_session()

        season_row = (session.query(
            SeasonInfo.current_season).filter(SeasonInfo.id == 1).first())
        season = season_row.current_season

        dt = TimeService.get_time()

        # Update the player's team to the new team
        for player in (session.query(ActiveMLBPlayers.player_id).filter(
                ActiveMLBPlayers.player_id == player_id).filter(
                    season == season)):
            session.query(ActiveMLBPlayers.player_id).filter(
                ActiveMLBPlayers.team_id).update({"team_id": team_id})

        # Update the InterLeague Trade Table
        hitter_trade = InterleagueTrades(
            player_id=player_id,
            season=season,
            home_runs=hr,
            batting_average=ba,
            at_bats=ab,
            hits=hits,
            plate_appearances=pa,
            player_games_played=games,
            RBI=rbi,
            update_date=dt,
        )

        session.add(hitter_trade)

        session.commit()
        session.close()
Ejemplo n.º 18
0
    def new_season_get(self):
        """Update the year to a new season"""
        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        session.close()

        vm = NewSeasonViewModel()
        return vm.to_dict()
Ejemplo n.º 19
0
    def update_mlb_players(self):
        """If MLB players have been added, run this to add any players that may not have been processed"""
        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        session.close()

        vm = UpdateMLBPlayersViewModel()
        return vm.to_dict()
Ejemplo n.º 20
0
    def new_install_get(self):
        """For first time installation, create the team, division, league, pick_types and points tables"""
        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        session.close()

        vm = NewInstallViewModel()
        return vm.to_dict()
Ejemplo n.º 21
0
    def add_mlb_players(self):
        """After updating to a new season, get a list of all MLB players for that season"""
        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        session.close()

        vm = UpdateMLBPlayersViewModel()
        return vm.to_dict()
Ejemplo n.º 22
0
    def all_star_break(all_star_break_date):
        """Get the date of the All Star Game from the database and create the window when a user can change picks"""

        # Get the All-Star break info from the database
        session = DbSessionFactory.create_session()
        all_star_game_query = session.query(SeasonInfo.all_star_game_date).first()
        all_star_game_date_string = str(all_star_game_query[0])
        all_star_game_datetime = pendulum.parse(all_star_game_date_string, tz=timezone)

        converted_date = pendulum.instance(all_star_game_datetime)
        all_star_game = converted_date.at(19)
        # print(all_star_game)

        season_start_date = season_opener()

        # print("Converted:", all_star_game)
        # print("Now time:", all_star_break_date)

        all_star_game_break_start = all_star_game.subtract(hours=48)
        # print("Break starts at", all_star_game_break_start)
        all_star_break_end = all_star_game.add(hours=48)
        # print("Break ends at", all_star_break_end)

        session.close()

        if all_star_break_date > all_star_break_end:
            print("The current date is greater than the when the break ends")
            return False

        elif all_star_break_date < season_start_date:

            return True

        elif all_star_game_break_start < all_star_break_date < all_star_break_end:

            return True

        elif all_star_break_date < all_star_game_break_start:
            print("The current date is less than the start of the all-star break")
            return False

        else:
            # print(False)
            return False
Ejemplo n.º 23
0
    def update_weekly_stats(self):
        """Update the stats"""
        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        vm = UpdateWeeklyStats()

        session.close()

        return vm.to_dict()
Ejemplo n.º 24
0
    def get_team_rankings():
        session = DbSessionFactory.create_session()

        season_row = session.query(SeasonInfo).filter(
            SeasonInfo.id == "1").first()
        season = season_row.current_season

        response = requests.get(
            "https://api.mysportsfeeds.com/v2.0/pull/mlb/" + str(season) +
            "-regular/standings.json",
            auth=HTTPBasicAuth(config.msf_api, config.msf_v2pw),
        )

        standings_json = response.json()
        standings_data = standings_json["teams"]

        x = 0

        for teams in standings_data:
            team_id = standings_data[x]["team"]["id"]
            division_rank = standings_data[x]["divisionRank"]["rank"]
            playoff_rank = standings_data[x]["playoffRank"]["rank"]
            team_wins = standings_data[x]["stats"]["standings"]["wins"]
            games_played = standings_data[x]["stats"]["gamesPlayed"]
            update_date = get_update_date()

            weekly_team_stats = WeeklyTeamStats(
                team_id=team_id,
                season=season,
                team_wins=team_wins,
                division_rank=division_rank,
                league_rank=playoff_rank,
                team_games_played=games_played,
                update_date=update_date,
            )

            x += 1

            session.add(weekly_team_stats)
            session.commit()

        session.close()
Ejemplo n.º 25
0
    def update_unique_picks(self):
        """Right after the season starts and right after the All-Star Break when pick changes are complete,
        run this to see what picks are unique for each pool player"""
        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        vm = UniquePicksViewModel()

        session.close()

        return vm.to_dict()
Ejemplo n.º 26
0
    def list_accounts(self):
        """Show list of accounts"""

        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        account_list = AccountService.get_all_accounts()

        session.close()

        return {"account_list": account_list}
Ejemplo n.º 27
0
def season_opener():

    session = DbSessionFactory.create_session()

    season_start_query = session.query(SeasonInfo.season_start_date).first()
    # print("Season Start Query:", season_start_query)

    # season_start_query is returned as a tuple and need to get the first part of the tuple:
    season_opener_date = str(season_start_query[0])

    # Convert the start date to a string that Pendulum can work with
    # season_start_date_convert = \
    #    pendulum.from_format(season_opener_date, '%Y-%m-%d %H:%M:%S', timezone).to_datetime_string()

    # Use the string above in a Pendulum instance and get the time deltas needed
    season_start_date = pendulum.parse(season_opener_date, tz=timezone)

    session.close()

    return season_start_date
Ejemplo n.º 28
0
    def get_pitcher_trade(
        cls,
        player_id: int,
        team_id: int,
        games: int,
        saves: int,
        era: float,
        er: int,
        ip: float,
    ):
        # Update the database with the new information

        session = DbSessionFactory.create_session()

        season_row = (session.query(
            SeasonInfo.current_season).filter(SeasonInfo.id == 1).first())
        season = season_row.current_season

        dt = TimeService.get_time()

        for player in (session.query(ActiveMLBPlayers.player_id).filter(
                ActiveMLBPlayers.player_id == player_id).filter(
                    season == season)):
            session.query(ActiveMLBPlayers.player_id).filter(
                ActiveMLBPlayers.team_id).update({"team_id": team_id})

        # Update the InterLeague Trade Table
        pitcher_trade = InterleagueTrades(
            season=season,
            player_id=player_id,
            player_games_played=games,
            saves=saves,
            ERA=era,
            earned_runs=er,
            innings_pitched=ip,
            update_date=dt,
        )
        session.add(pitcher_trade)

        session.commit()
        session.close()
Ejemplo n.º 29
0
    def make_admin(self):
        """GET request to make a pool player an administrator."""
        vm = AdminViewModel()

        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        pool_player_list = AccountService.get_all_accounts()

        session.close()

        return {"players": pool_player_list}
Ejemplo n.º 30
0
    def payment(self):
        """Update if a player has paid the season fee."""
        vm = AdminViewModel()

        session = DbSessionFactory.create_session()
        su__query = (
            session.query(Account.id)
            .filter(Account.is_super_user == 1)
            .filter(Account.id == self.logged_in_user_id)
            .first()
        )

        if su__query is None:
            print("You must be an administrator to view this page")
            self.redirect("/home")

        player_list = AccountService.get_all_accounts()

        session.close()

        return {"players": player_list}