def pull_games(url, team_lookup, league_lookup): """ pull_games Returns a lookup of games that were pulled from the website into local DB Parameters: url: the url of the main site Returns: a dictionary lookup for the website game id to local game object e.g. game_lookup = {1: Game(), etc..} """ _games = requests.get(url + "/api/games").json() if isinstance(_games, dict): _games = pull_all_pages(url, _games) game_lookup = {} for game in tqdm(_games, desc="Pulling games from {}".format(url)): temp = Game(game['date'], game['time'], team_lookup[game['home_team_id']].id, team_lookup[game['away_team_id']].id, league_lookup[game['league_id']].id, status=game['status'], field=game['field']) game_lookup[game['game_id']] = temp DB.session.add(temp) DB.session.commit() return game_lookup
def game_without_score(team_id: int): """Ensure the given team has a game today""" games = games_without_scores(team_id) if len(games) == 0: today = datetime.now() other_team = Team.query.filter( and_(Team.year == today.year, Team.id != team_id)).first() division = Division.query.first() game = Game(today.strftime("%Y-%m-%d"), "12:00", team_id, other_team.id, other_team.league_id, division.id, 'today game', 'WP1') DB.session.add(game) DB.session.commit() else: game = games[0] return Response(json.dumps(game.json()), 200, mimetype='application/json')
def post(self): """ POST request for Games List Route: Routes['game'] Parameters : home_team_id: The home team id (int) away_team_id: The away team id (int) date: The date of the game with the format YYYY-MM-DD (string) time: The time of the game in the format HH:MM (string) league_id: The league this game belongs to (int) status: the game status (string) field: the field the game is being played on (string) Returns: if successful status: 200 mimetype: application/json data: the created game id (int) """ # create a new game args = post_parser.parse_args() date = None time = None if args['date'] and args['time']: date = args['date'] time = args['time'] status = args.get('status') if args.get('status') is not None else '' field = args.get('field') if args.get('field') is not None else '' game = Game(date, time, args.get('home_team_id'), args.get('away_team_id'), args.get('league_id'), args.get('division_id'), status=status, field=field) DB.session.add(game) DB.session.commit() result = game.id handle_table_change(Tables.GAME, item=game.json()) return Response(dumps(result), status=201, mimetype="application/json")
def post(self): """ POST request for Games List Route: Routes['game'] Parameters : home_team_id: The home team id (int) away_team_id: The away team id (int) date: The date of the game with the format YYYY-MM-DD (string) time: The time of the game in the format HH:MM (string) league_id: The league this game belongs to (int) status: the game status (string) field: the field the game is being played on (string) Returns: if successful status: 200 mimetype: application/json data: the created game id (int) """ # create a new game args = post_parser.parse_args() home_team_id = None away_team_id = None date = None time = None league_id = None status = "" field = "" if args['home_team_id']: home_team_id = args['home_team_id'] if args['away_team_id']: away_team_id = args['away_team_id'] if args['date'] and args['time']: date = args['date'] time = args['time'] if args['league_id']: league_id = args['league_id'] if args['status']: status = args['status'] if args['field']: field = args['field'] game = Game(date, time, home_team_id, away_team_id, league_id, status=status, field=field) DB.session.add(game) DB.session.commit() result = game.id return Response(dumps(result), status=201, mimetype="application/json")
def testGameInit(self): sponsor = self.add_sponsor("TestModelSponsor") league = self.add_league("TestModelLeague") league_id = league['league_id'] home_team_id = self.add_team("TestModelHomeTeam", sponsor, league, VALID_YEAR)['team_id'] away_team_id = self.add_team("TestModelAwayTeam", sponsor, league, VALID_YEAR)['team_id'] # good game Game(self.d, self.t, home_team_id, away_team_id, league_id) try: Game("x", self.t, home_team_id, away_team_id, league_id) self.assertEqual(True, False, "should raise invalid field") except InvalidField: pass try: Game(self.d, self.t, home_team_id, away_team_id, league_id, status=1) self.assertEqual(True, False, "should raise invalid field") except InvalidField: pass try: Game(self.d, self.t, home_team_id, away_team_id, league_id, field=1) self.assertEqual(True, False, "should raise invalid field") except InvalidField: pass try: Game(self.d, self.t, INVALID_ID, away_team_id, league_id) self.assertEqual(True, False, "should raise no team") except TeamDoesNotExist: pass try: Game(self.d, self.t, home_team_id, INVALID_ID, league_id) self.assertEqual(True, False, "should raise no team") except TeamDoesNotExist: pass try: Game(self.d, self.t, home_team_id, away_team_id, INVALID_ID) self.assertEqual(True, False, "should raise no league") except LeagueDoesNotExist: pass
def import_league_functional(self): """ Add a team to the database using functions instead of methods""" # parse out the parts - background, header, players parts = parse_parts(self.lines) self.warnings = parts['warnings'] # extract the background such a league, sponsor and color background = extract_background(parts['background']) league = background["league"] division = background["division"] # extract the players using the header as lookup lookup = extract_column_indices_lookup(parts['header']) # get the team map team_lookup = get_team_lookup(league) # extract the games games = extract_games(parts["games"], team_lookup, lookup) self.warnings = self.warnings + games['warnings'] # add the players for game_json in games['games']: try: game = Game(game_json["date"], game_json["time"], game_json["home_team_id"], game_json["away_team_id"], league["league_id"], division["division_id"], field=game_json["field"]) self.session.add(game) except Exception as error: game_list = [str(value) for value in game_json.values()] game_info = "-".join(game_list) self.warnings.append(INVALID_GAME.format(game_info, str(error))) self.session.commit()
def import_game(self, info): ''' a method the imports one game Parameters: info: the string that contains the information of a player (str) Returns: ''' info = info.split(",") if (len(info) < self.away_index or len(info) < self.home_index or len(info) < self.time_index or len(info) < self.field_index or len(info) < self.date_index): s = "Game did not have the right number of fields" self.logger.debug(s) return # probably just an empty line away = info[self.away_index].strip() home = info[self.home_index].strip() time = info[self.time_index].strip() field = info[self.field_index].strip() date = info[self.date_index].strip() # check if variables meet certain conditions # else should be good to add game away_team = self.teams.get(away, None) home_team = self.teams.get(home, None) if away_team is None: self.errors.append(INVALID_TEAM.format(away)) if home_team is None: self.errors.append(INVALID_TEAM.format(home)) if away_team is not None and home_team is not None: # else should be good to add the game game = Game(date, time, home_team, away_team, self.league_id, field=field) self.session.add(game) return
def testGameUpdate(self): self.insertTeams() # good game g = Game(self.d, self.t, 1, 2, 1) try: __= Game("x", self.t, 1, 2, 1) self.assertEqual(True, False, "should raise invalid field") except InvalidField: pass try: g.update(self.d, self.t, 1, 2, 1, status=1) self.assertEqual(True, False, "should raise invalid field") except InvalidField: pass try: g.update(self.d, self.t, 1, 2, 1, field=1) self.assertEqual(True, False, "should raise invalid field") except InvalidField: pass try: g.update(self.d, self.t, 999, 2, 1) self.assertEqual(True, False, "should raise no team") except TeamDoesNotExist: pass try: g.update(self.d, self.t, 1, 999, 1) self.assertEqual(True, False, "should raise no team") except TeamDoesNotExist: pass try: g.update(self.d, self.t, 1, 2, 999) self.assertEqual(True, False, "should raise no league") except LeagueDoesNotExist: pass
def mock_teams_games(league, sponsor_lookup): """ mock_team_games Mocks up some data for the league by add some players to a team, then a few games to the league and a few scores for some games Parameters: league: the league object sponsor_lookup: a dictionary lookup for a id to its given sponsor Returns: None """ # add some players domain = "@" + league.name.replace(" ", "") team_one_players = [ Player("Captain1", "captain1" + domain, gender="M"), Player("MalePlayer1", "mp1" + domain, gender="M"), Player("FemalePlayer1", "fp1" + domain, gender="F") ] team_two_players = [ Player("Captain2", "captain2" + domain, gender="F"), Player("MalePlayer2", "mp2" + domain, gender="M"), Player("FemalePlayer2", "fp2" + domain, gender="F") ] team_three_players = [ Player("Captain3", "captain3" + domain, gender="M"), Player("MalePlayer3", "mp3" + domain, gender="M"), Player("FemalePlayer3", "fp3" + domain, gender="F") ] team_four_players = [ Player("Captain4", "captain4" + domain, gender="F"), Player("MalePlayer4", "mp4" + domain, gender="M"), Player("FemalePlayer4", "fp4" + domain, gender="F") ] team_players = [ team_one_players, team_two_players, team_three_players, team_four_players ] for team in tqdm(team_players, desc="Adding mock Players"): for player in team: DB.session.add(player) DB.session.commit() # add four teams with some players teams = [ Team(color="Black", sponsor_id=random_value_lookup(sponsor_lookup).id, league_id=league.id), Team(color="Blue", sponsor_id=random_value_lookup(sponsor_lookup).id, league_id=league.id), Team(color="Red", sponsor_id=random_value_lookup(sponsor_lookup).id, league_id=league.id), Team(color="Green", sponsor_id=random_value_lookup(sponsor_lookup).id, league_id=league.id) ] for i in tqdm(range(0, len(teams)), desc="Adding mock players to Teams"): team = teams[i] DB.session.add(team) # add the players to the team for player in team_players[i]: team.insert_player(player.id, "captain" in player.name.lower()) DB.session.commit() # add some random espsy to each team and # create a lookup for team id to players team_player_lookup = {} random_prices = [9.99, 4.75, 100, 15.50, 12.99] for i in tqdm(range(0, len(teams)), desc="Adding mock espys to Teams"): team_player_lookup[team.id] = team_players[i] team = teams[i] for __ in range(0, 4): points = random_value_list(random_prices) espy = Espys(team.id, sponsor_id=random_value_lookup(sponsor_lookup).id, description="Purchase", points=points) DB.session.add(espy) DB.session.commit() # add some games between the teams # need a bunch of games today = datetime.date.today() games = [] for day in range(-3, 3): date_string = (today + datetime.timedelta(days=day)).strftime("%Y-%m-%d") status = "Completed" if day < 0 else "To Be Played" games.append( Game(date_string, "10:00", teams[0].id, teams[1].id, league.id, status=status, field="WP1")) games.append( Game(date_string, "10:00", teams[2].id, teams[3].id, league.id, status=status, field="WP2")) games.append( Game(date_string, "11:00", teams[0].id, teams[2].id, league.id, status=status, field="WP1")) games.append( Game(date_string, "11:00", teams[2].id, teams[1].id, league.id, status=status, field="WP2")) games.append( Game(date_string, "12:00", teams[0].id, teams[3].id, league.id, status=status, field="WP1")) games.append( Game(date_string, "12:00", teams[2].id, teams[1].id, league.id, status=status, field="WP2")) for game in tqdm(games, "Adding mock games"): DB.session.add(game) DB.session.commit() # now add a random score to the game for game in tqdm(games[:18], desc="Mocking scores for games"): add_random_score(game.id, game.away_team_id, team_player_lookup[game.away_team_id]) add_random_score(game.id, game.home_team_id, team_player_lookup[game.home_team_id]) DB.session.commit()
def testGameUpdate(self): sponsor = self.add_sponsor(str(uuid.uuid1())) league = self.add_league(str(uuid.uuid1())) league_id = league['league_id'] division = self.add_division(str(uuid.uuid1())) division_id = division['division_id'] home_team_id = self.add_team(str(uuid.uuid1()), sponsor, league, VALID_YEAR)['team_id'] away_team_id = self.add_team(str(uuid.uuid1()), sponsor, league, VALID_YEAR)['team_id'] # good game g = Game(getDateString(), getTimeString(), home_team_id, away_team_id, league_id, division_id) try: g.update(getDateString(), getTimeString(), home_team_id, away_team_id, league_id, status=1) self.assertEqual(True, False, "should raise invalid field") except InvalidField: pass try: g.update(getDateString(), getTimeString(), home_team_id, away_team_id, league_id, field=1) self.assertEqual(True, False, "should raise invalid field") except InvalidField: pass try: g.update(getDateString(), getTimeString(), INVALID_ID, away_team_id, league_id) self.assertEqual(True, False, "should raise no team") except TeamDoesNotExist: pass try: g.update(getDateString(), getTimeString(), home_team_id, INVALID_ID, league_id) self.assertEqual(True, False, "should raise no team") except TeamDoesNotExist: pass try: g.update(getDateString(), getTimeString(), home_team_id, away_team_id, INVALID_ID) self.assertEqual(True, False, "should raise no league") except LeagueDoesNotExist: pass