def __init__(self, color=None, sponsor_id=None, league_id=None, year=date.today().year): """ The constructor. Raises InvalidField SponsorDoesNotExist LeagueDoesNotExist """ if color is not None and not string_validator(color): raise InvalidField(payload={'details': "Team - color"}) if sponsor_id is not None and Sponsor.query.get(sponsor_id) is None: raise SponsorDoesNotExist(payload={'details': sponsor_id}) if league_id is not None and League.query.get(league_id) is None: raise LeagueDoesNotExist(payload={'details': league_id}) if year is not None and not year_validator(year): raise InvalidField(payload={'details': "Team - year"}) self.color = color self.sponsor_id = sponsor_id self.league_id = league_id self.year = year self.kik = None
def update(self, name: str = None, link: str = None, description: str = None, active: bool = None) -> None: """Updates an existing sponsor. Raises: InvalidField """ if name is not None and string_validator(name): self.name = name elif name is not None: raise InvalidField(payload={'details': "Sponsor - name"}) if description is not None and string_validator(description): self.description = description elif description is not None: raise InvalidField(payload={'details': "Sponsor - description"}) if link is not None and string_validator(link): self.link = link elif link is not None: raise InvalidField(payload={'details': "Sponsor - link"}) if active is not None and boolean_validator(active): self.active = active elif active is not None: raise InvalidField(payload={'detail': "Player - active"})
def extract_background(background): """Returns a dictionary of the extracted json objects from the background. Parameters: background: dictionary of sponsor, color, captain, league Returns: a dictionary of league model """ background_keys = [key.lower() for key in background.keys()] for value in BACKGROUND.values(): if value.lower() not in background_keys: errorMessage = MISSING_BACKGROUND.format(value) raise InvalidField(payload={"details": errorMessage}) # ensure able to find the division division_name = background['division'] if division_name.lower().startswith("ex."): error_message = LEFT_BACKGROUND_EXAMPLE.format(division_name) raise InvalidField(payload={"details": error_message}) division = Division.query.filter(func.lower(Division.name) == func.lower(division_name)).first() # ensure able to find the league league_name = background['league'] if league_name.lower().startswith("ex."): error_message = LEFT_BACKGROUND_EXAMPLE.format(league_name) raise InvalidField(payload={"details": error_message}) league = League.query.filter(func.lower(League.name) == func.lower(league_name)).first() if division is None: error_message = INVALID_DIVISION.format(division_name) raise DivisionDoesNotExist(payload={'details': error_message}) if league is None: error_message = INVALID_LEAGUE.format(league_name) raise LeagueDoesNotExist(payload={'details': error_message}) return {"league": league.json(), "division": division.json()}
def __init__(self, name, link=None, description=None, active=True, nickname=None): """The constructor. Raises: InvalidField """ if not string_validator(name): raise InvalidField(payload={'details': "Sponsor - name"}) if not string_validator(link): raise InvalidField(payload={'details': "Sponsor - link"}) if not string_validator(description): raise InvalidField(payload={'details': "Sponsor - description"}) self.name = name self.description = description self.link = link self.active = active if nickname is None: self.nickname = name else: self.nickname = nickname
def update(self, color=None, sponsor_id=None, league_id=None, year=None): """Updates an existing team. Raises: InvalidField SponsorDoesNotExist LeagueDoesNotExist """ # does nothing with espys given if color is not None and string_validator(color): self.color = color elif color is not None: raise InvalidField(payload={'details': "Team - color"}) if (sponsor_id is not None and Sponsor.query.get(sponsor_id) is not None): self.sponsor_id = sponsor_id elif sponsor_id is not None: raise SponsorDoesNotExist(payload={'details': sponsor_id}) if league_id is not None and League.query.get(league_id) is not None: self.league_id = league_id elif league_id is not None: raise LeagueDoesNotExist(payload={'details': league_id}) if year is not None and year_validator(year): self.year = year elif year is not None: raise InvalidField(payload={'details': "Team - year"})
def __init__(self, name, email, gender=None, password="******", active=True): """The constructor. Raises: InvalidField NonUniqueEmail """ if not string_validator(name): raise InvalidField(payload={"details": "Player - name"}) # check if email is unique if not string_validator(email): raise InvalidField(payload={'details': "Player - email"}) player = Player.query.filter_by(email=email).first() if player is not None: raise NonUniqueEmail(payload={'details': email}) if gender is not None and not gender_validator(gender): raise InvalidField(payload={'details': "Player - gender"}) self.name = name self.email = email if gender is not None: gender = gender.lower() self.gender = gender self.set_password(password) self.active = active
def update(self, date: str = None, time: str = None, home_team_id: int = None, away_team_id: int = None, league_id: int = None, status: str = None, field: str = None, division_id: int = None) -> None: """Update an existing game. Raises: InvalidField TeamDoesNotExist LeagueDoesNotExist """ d = self.date.strftime("%Y-%m-%d") t = self.date.strftime("%H:%M") if date is not None and date_validator(date): d = date elif date is not None: raise InvalidField(payload={'details': "Game - date"}) if time is not None and time_validator(time): t = time elif time is not None: raise InvalidField(payload={'details': "Game - time"}) if (home_team_id is not None and Team.query.get(home_team_id) is not None): self.home_team_id = home_team_id elif home_team_id is not None: raise TeamDoesNotExist(payload={'details': home_team_id}) if (away_team_id is not None and Team.query.get(away_team_id) is not None): self.away_team_id = away_team_id elif away_team_id is not None: raise TeamDoesNotExist(payload={'details': away_team_id}) if league_id is not None and League.query.get(league_id) is not None: self.league_id = league_id elif league_id is not None: raise LeagueDoesNotExist(payload={'details': league_id}) if status is not None and string_validator(status): self.status = status elif status is not None: raise InvalidField(payload={'details': "Game - status"}) if field is not None and field_validator(field): self.field = field elif field is not None: raise InvalidField(payload={'details': "Game - field"}) if (division_id is not None and Division.query.get(division_id) is not None): self.division_id = division_id elif division_id is not None: raise DivisionDoesNotExist(payload={'details': "division_id"}) # worse case just overwrites it with same date or time self.date = datetime.strptime(d + "-" + t, '%Y-%m-%d-%H:%M')
def __init__(self, name: str, shortname: str = None): """The constructor Raises: InvalidField """ if not string_validator(name): raise InvalidField(payload={'details': "Division - name"}) if shortname is not None and not string_validator(shortname): raise InvalidField(payload={'details': "Division - short name"}) self.name = name self.shortname = shortname
def update(self, name: str = None, shortname: str = None) -> None: """Update an existing division. Raises: InvalidField """ if name is not None and not string_validator(name): raise InvalidField(payload={'details': "Division - name"}) if shortname is not None and not string_validator(shortname): raise InvalidField(payload={'details': "Division - shortname"}) if name is not None: self.name = name if shortname is not None: self.shortname = shortname
def __init__(self, email: str, name: str, team: 'Team', gender: str): if team is None or not isinstance(team, Team) or team.id is None: raise TeamDoesNotExist("Given team does not exist") if not gender_validator(gender): raise InvalidField(payload={ 'details': "Player League Request - gender"}) if not string_validator(email): raise InvalidField(payload="Player League Request - email") if not string_validator(name): raise InvalidField(payload="Player League Request - name") self.email = email.lower() self.name = name self.team_id = team.id self.pending = True self.gender = gender.lower()
def import_players(self, player_index): """Import a list of players""" while (player_index < len(self.lines) and len(self.lines[player_index].split(",")) > 1): info = self.lines[player_index].split(",") self.logger.debug(info, len(info)) if len(info) < 3: raise InvalidField(payload={"details": "Missing a category"}) name = info[self.name_index].strip() email = info[self.email_index].strip() gender = info[self.gender_index].strip() if not name.lower().startswith("ex."): player = (DB.session.query(Player).filter( Player.email == email)).first() if player is None: self.logger.debug(name + " " + email + " " + gender) player = Player(name, email, gender=gender) self.session.add(player) self.logger.debug("Player was created") else: # this player is active player.active = True self.team.players.append(player) if name == self.captain_name: self.captain = player else: self.warnings.append("Player Example was left") player_index += 1 return
def post(self): """ POST request for retrieving a captain games that needs scores submitted Route: Route['botcaptaingames'] Parameters: team: the team's id (str) player_id: the captain's player_id (int) Returns: status: 200 mimetype: application/json result: list of games objects """ args = parser.parse_args() team_id = args['team'] player_id = args['player_id'] team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) if team.player_id is None: raise InvalidField( payload={"details": "Team's captain has not been set"}) if player_id != team.player_id: # something fishy is going on raise NotTeamCaptain(payload={'details': player_id}) # captain is authenticated # now get the teams games, that have past game date and have no bats result = [game.json() for game in games_without_scores(team_id)] return Response(dumps(result), status=200, mimetype="application/json")
def import_league(self): ''' a method that imports a bunch of games for a league based on a csv template Parameters: Updates: success: a boolean if the import was successful (boolean) errors: a list of possible error (list) warnings: a list of possible warnings (list) ''' if self.lines is None: raise InvalidField("No lines were provided") if self.check_header(self.lines[0:2]): league, headers = self.parse_header(self.lines[0:2]) self.logger.debug("Getting League ID") self.league_id = self.get_league_id(league) self.logger.debug("Got League id {}".format(self.league_id)) self.set_columns_indices(headers) self.logger.debug("Got set column indcides") if self.league_id is not None: self.set_teams() games = self.lines[2:] for game in games: self.logger.debug(game) self.import_game(game) self.logger.debug("Done Import") else: self.errors.append(INVALID_FILE) if len(self.errors) < 1: self.logger.debug("Committing") # no major errors so commit changes self.session.commit() return
def post(self): """ POST request for League Leaders Route: Route['vleagueleaders'] Parameters: year: the year (int) stat: the stat to order by (str) group_by_team: whether to group by team or not (int) default=True Returns: status: 200 mimetype: application/json data: list of Players """ year = None stat = None group_by_team = True args = parser.parse_args() if args['year']: year = args['year'] if args['stat'] and hit_validator(args['stat']): stat = args['stat'] else: raise InvalidField(payload={'details': 'Invalid stat'}) if args['group_by_team'] == 0: group_by_team = False if group_by_team: players = get_leaders(stat, year=year) else: players = get_leaders_not_grouped_by_team(stat, year=year) return Response(dumps(players), status=200, mimetype="application/json")
def subscribe(kik, name, team_id): """A function used to subscribe a kik user name to a player. Parameters: kik: the kik user name name: the name of the player team_id: the id of the team the player belongs to Returns: True Raises: TeamDoesNotExist PlayerNotOnTeam """ # dont care if they are on the team # check for some goof player = Player.query.filter_by(kik=kik).filter_by(active=True).all() if len(player) > 1 and player[0].name != name: s = "Kik user subscribing as two different people" raise BadRequestError(payload={'details': s}) team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) player = Player.query.filter_by(name=name).filter_by(active=True).all() if len(player) > 1: # f**k i dont know raise InvalidField("Two people with exact name, email the convenors") elif player is None or len(player) == 0: # player is not officially in our db # going to add them as a guest player = Player(name, name + "@guest", gender="M", password="******", active=False) DB.session.add(player) DB.session.commit() else: player = player[0] if player.kik is None: # give them the two points player.kik = kik points_awarded = Espys(team_id, description=AWARD_POINTS.format( str(player), KIKPOINTS), points=KIKPOINTS) DB.session.add(points_awarded) elif player.kik != kik: # the player is subscribing under a new kik name player.kik = kik subscribed = (Espys.query.filter_by(team_id=team_id).filter_by( description=SUBSCRIBED.format(str(player)))).first() if subscribed is None: # player is not subscribed subscribed = Espys(team_id, description=SUBSCRIBED.format(str(player)), points=0) DB.session.add(subscribed) DB.session.commit() return True
def __init__(self, name=None): """The constructor. Raises: InvalidField """ if not string_validator(name): raise InvalidField(payload={'details': "League - name"}) self.name = name
def update(self, league): """Update an existing league. Raises: InvalidField """ if not string_validator(league): raise InvalidField(payload={'details': "League - name"}) self.name = league
def __init__(self, date: str, time: str, home_team_id: int, away_team_id: int, league_id: int, division_id: int, status: str = "", field: str = ""): """The Constructor. Raises: InvalidField TeamDoesNotExist LeagueDoesNotExist DivisionDoesNotExist """ # check for all the invalid parameters if not date_validator(date): raise InvalidField(payload={'details': "Game - date"}) if not time_validator(time): raise InvalidField(payload={'details': "Game - time"}) self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M') if (home_team_id is None or Team.query.get(home_team_id) is None): raise TeamDoesNotExist(payload={'details': home_team_id}) if (away_team_id is None or Team.query.get(away_team_id) is None): raise TeamDoesNotExist(payload={'details': away_team_id}) if League.query.get(league_id) is None: raise LeagueDoesNotExist(payload={'details': league_id}) if ((status != "" and not string_validator(status)) or (field != "" and not field_validator(field))): raise InvalidField(payload={'details': "Game - field/status"}) if Division.query.get(division_id) is None: raise DivisionDoesNotExist(payload={'details': division_id}) # must be good now self.home_team_id = home_team_id self.away_team_id = away_team_id self.league_id = league_id self.status = status self.field = field self.division_id = division_id
def set_columns_indices(self, header): ''' a method that set the indices for the column headers Parameters: header: the list of columns for the header (list of str) Returns: ''' for i in range(0, len(header)): if "email" in header[i].lower(): self.email_index = i elif "name" in header[i].lower(): self.name_index = i elif "gender" in header[i].lower(): self.gender_index = i if self.email_index is None: raise InvalidField(payload={'details': "Email header missing"}) if self.name_index is None: raise InvalidField(payload={'details': "Player header missing"}) if self.gender_index is None: raise InvalidField(payload={'details': "Gender header missing"}) return
def __init__(self, team_id, sponsor_id=None, description=None, points=0.0, receipt=None, time=None, date=None): """The constructor. Raises: SponsorDoesNotExist TeamDoesNotExist """ if not float_validator(points): raise InvalidField(payload={"details": "Game - points"}) self.points = float(points) self.date = datetime.now() sponsor = None if sponsor_id is not None: sponsor = Sponsor.query.get(sponsor_id) self.receipt = receipt if sponsor_id is not None and sponsor is None: raise SponsorDoesNotExist(payload={"details": sponsor_id}) team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={"details": team_id}) self.description = description self.team_id = team_id self.sponsor_id = sponsor_id self.kik = None if date is not None and not date_validator(date): raise InvalidField(payload={'details': "Game - date"}) if time is not None and not time_validator(time): raise InvalidField(payload={'details': "Game - time"}) if date is not None and time is None: self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M') else: self.date = datetime.today()
def update(self, player_id=None, team_id=None, game_id=None, rbi=None, hit=None, inning=None): """Update an existing bat. Raises: TeamDoesNotExist GameDoesNotExist PlayerDoesNotExist InvalidField """ if team_id is not None and Team.query.get(team_id) is not None: self.team_id = team_id elif team_id is not None: raise TeamDoesNotExist(payload={'details': team_id}) if game_id is not None and Game.query.get(game_id) is not None: self.game_id = game_id elif game_id is not None: raise GameDoesNotExist(payload={'details': game_id}) if player_id is not None and Player.query.get(player_id) is not None: self.player_id = player_id elif player_id is not None: raise PlayerDoesNotExist(payload={'details': player_id}) if rbi is not None and rbi_validator(rbi): self.rbi = rbi elif rbi is not None: raise InvalidField(payload={'details': "Bat - rbi"}) if hit is not None and hit_validator(hit): self.classification = hit elif hit is not None: raise InvalidField(payload={'details': "Bat - hit"}) if inning is not None and inning_validator(inning): self.inning = inning elif inning is not None: raise InvalidField(payload={'details': "Bat - inning"})
def submit_score(game_id: int, captain_id: int, score: int, homeruns: List[int], ss: List[int]) -> bool: """Captain submit a score""" unassigned_player = Player.query.filter_by(email=UNASSIGNED_EMAIL).first() unassigned_id = UNASSIGNED if unassigned_player is not None: unassigned_id = unassigned_player.id game = Game.query.get(game_id) captain = Player.query.get(captain_id) if captain is None: raise PlayerNotSubscribed(payload={'details': captain_id}) if game is None: raise GameDoesNotExist(payload={'details': game_id}) # find the team away_team = Team.query.get(game.away_team_id) home_team = Team.query.get(game.home_team_id) team = None if away_team.player_id == captain.id: team = away_team # captain of the squad elif home_team.player_id == captain.id: team = home_team # captain of the away squad else: # not a captain of a team raise NotTeamCaptain(payload={'details': captain_id}) if score <= 0: # hmm that is so sad DB.session.add( Bat(unassigned_id, team.id, game.id, "fo", inning=1, rbi=0)) if homeruns is not None: for player_id in homeruns: # add the homeruns DB.session.add( Bat(player_id, team.id, game.id, "hr", inning=1, rbi=1)) score -= 1 if ss is not None: for player_id in ss: # add the special singles try: bat = Bat(player_id, team.id, game.id, "ss", inning=1, rbi=0) DB.session.add(bat) except InvalidField: pass if score < 0: raise InvalidField(payload={'details': "More hr than score"}) while score > 0: bat = Bat(unassigned_id, team.id, game.id, "s", inning=1, rbi=1) DB.session.add(bat) score -= 1 DB.session.commit() # good to add the submission handle_table_change(Tables.GAME) return True
def update(self, name: str = None, email: str = None, gender: str = None, password: str = None, active: bool = None) -> None: """Update an existing player Parameters: name: the name of the player email: the unique email of the player gender: the gender of the player password: the password of the player Raises: InvalidField NonUniqueEmail """ if email is not None: # check if email is unique if not string_validator(email): raise InvalidField(payload="Player - email") email = email.strip().lower() player = Player.query.filter_by(email=email).first() if player is not None: raise NonUniqueEmail(payload={'details': email}) self.email = email if gender is not None and gender_validator(gender): self.gender = gender.lower() elif gender is not None: raise InvalidField(payload={'details': "Player - gender"}) if name is not None and string_validator(name): self.name = name elif name is not None: raise InvalidField(payload={'details': "Player - name"}) if active is not None and boolean_validator(active): self.active = active elif active is not None: raise InvalidField(payload={'detail': "Player - active"})
def update(self, team_id=None, sponsor_id=None, description=None, points=None, receipt=None, date=None, time=None): """Used to update an existing espy transaction. Raises: TeamDoesNotExist SponsorDoesNotExist """ if points is not None: self.points = points if description is not None: self.description = description if team_id is not None: if Team.query.get(team_id) is not None: self.team_id = team_id else: raise TeamDoesNotExist(payload={"details": team_id}) if sponsor_id is not None: if Sponsor.query.get(sponsor_id) is not None: self.sponsor_id = sponsor_id else: raise SponsorDoesNotExist(payload={"details": sponsor_id}) if receipt is not None: self.receipt = receipt if date is not None and time is None: self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M') if date is not None and time is not None: if date is not None and not date_validator(date): raise InvalidField(payload={'details': "Game - date"}) if time is not None and not time_validator(time): raise InvalidField(payload={'details': "Game - time"}) self.date = datetime.strptime(date + "-" + time, '%Y-%m-%d-%H:%M')
def __init__(self, player_id, team_id, game_id, classification, inning=1, rbi=0): """The constructor. Raises: PlayerDoesNotExist InvalidField TeamDoesNotExist GameDoesNotExist """ # check for exceptions classification = classification.lower().strip() player = Player.query.get(player_id) if player is None: raise PlayerDoesNotExist(payload={'details': player_id}) if not hit_validator(classification, player.gender): raise InvalidField(payload={'details': "Bat - hit"}) if not rbi_validator(rbi): raise InvalidField(payload={'details': "Bat - rbi"}) if not inning_validator(inning): raise InvalidField(payload={'details': "Bat - inning"}) if Team.query.get(team_id) is None: raise TeamDoesNotExist(payload={'details': team_id}) if Game.query.get(game_id) is None: raise GameDoesNotExist(payload={'details': game_id}) # otherwise good and a valid object self.classification = classification self.rbi = rbi self.player_id = player_id self.team_id = team_id self.game_id = game_id self.inning = inning
def post(self): """ POST request for retrieving a captain games that needs scores submitted Route: Route['kikcaptaingames'] Parameters: team: the team's id (str) kik: the captain's kik user name (str) Returns: status: 200 mimetype: application/json result: list of games objects """ args = parser.parse_args() team_id = args['team'] kik = args['kik'] team = Team.query.get(team_id) if team is None: raise TeamDoesNotExist(payload={'details': team_id}) if team.player_id is None: raise InvalidField( payload={"details": "Team's captain has not been set"}) team_captain = Player.query.get(team.player_id) if team_captain is None: raise PlayerDoesNotExist(payload={'details': team.player_id}) if team_captain.kik != kik: # something fishy is going on raise NotTeamCaptain(payload={'details': team_captain.kik}) # captain is authenticated # get all the bats for that team and its game id bats = (DB.session.query( Bat.game_id).filter(Bat.team_id == team_id)).all() if (len(bats) > 0): games = (DB.session.query(Game).filter( or_(Game.away_team_id == team_id, Game.home_team_id == team_id)).filter( Game.date <= datetime.today()).filter( ~Game.id.in_(bats))).all() else: games = (DB.session.query(Game).filter( or_(Game.away_team_id == team_id, Game.home_team_id == team_id)).filter( Game.date <= datetime.today())).all() # now get the teams games, that have past game date and have no bats result = [] for game in games: result.append(game.json()) return Response(dumps(result), status=200, mimetype="application/json")
def admin_import_team_list(): results = {'errors': [], 'success': False, 'warnings': []} if not logged_in(): results['errors'].append("Permission denied") return dumps(results) file = request.files['file'] result = None if file and allowed_file(file.filename): content = (file.read()).decode("UTF-8") lines = content.replace("\r", "") lines = lines.split("\n") team = TeamList(lines) team.add_team() result = team.warnings else: s = "File format not accepted (csv)" raise InvalidField(payload={'detail': s}) return dumps(result)
def extract_column_indices_lookup(header): """ Returns a dictionary used to lookup indices for various fields Parameters: header: the header array Returns: a dictionary {str(field): int(index)} """ lookup = {} for i in range(0, len(header)): for key, value in HEADERS.items(): if is_entry_a_header(key, value, header[i]): lookup[key.lower()] = i # ensure all headers were found for key in HEADERS.keys(): if key not in lookup.keys(): error_message = "{} header missing".format(key.lower()) raise InvalidField(payload={'details': error_message}) return lookup
def import_headers(self): """Parse the headers of the csv and add team""" done = False i = 0 sponsor = None color = None captain = None league = None while not done: # read the headers line = self.lines[i] columns = line.split(",") if self.clean_cell(columns[0]) == "sponsor": sponsor = columns[1].strip() elif self.clean_cell(columns[0]) == "color": color = columns[1].strip() elif self.clean_cell(columns[0]) == "captain": captain = columns[1].strip() elif self.clean_cell(columns[0]) == "league": league = columns[1].strip() else: # assuming done reading the headers done = True i += 1 player_index = i if sponsor is None: raise InvalidField(payload={"details": "No sponsor was given"}) if captain is None: raise InvalidField(payload={"details": "No captain was given"}) if color is None: raise InvalidField(payload={"details": "No color was given"}) if league is None: raise InvalidField(payload={"details": "No league was given"}) # check no examples were left and actually real info if (league.lower().startswith("ex.") or sponsor.lower().startswith("ex.") or color.lower().startswith("ex.") or captain.lower().startswith("ex.")): t = "The header's still had an example" raise InvalidField(payload={"details": t}) sponsor_id = (DB.session.query(Sponsor).filter( Sponsor.name == sponsor).first()) if sponsor_id is None: sponsor_id = (DB.session.query(Sponsor).filter( Sponsor.nickname == sponsor).first()) if sponsor_id is None: # what kind of sponsor are you giving t = "The sponsor does not exist (check case)" raise SponsorDoesNotExist(payload={'details': t}) sponsor_id = sponsor_id.id league_id = (DB.session.query(League).filter( League.name == league)).first() if league_id is None: t = "The league does not exist (check case)" raise LeagueDoesNotExist(payload={"details": t}) league_id = league_id.id # check to see if team was already created teams = (DB.session.query(Team).filter(Team.color == color).filter( Team.sponsor_id == sponsor_id).filter( Team.year == date.today().year).all()) team_found = None if len(teams) > 0: team_found = teams[0] # was the team not found then should create it if team_found is None: self.warnings.append("Team was created") team_found = Team(color=color, sponsor_id=sponsor_id, league_id=league_id) else: team_found.players = [] # remove all the players before self.team = team_found # set the team self.captain_name = captain # remember captains name return player_index
def post(self): """ POST request for submitting Score Summaries Route: Route['kiksubmitscore'] Parameters: game_id: the game_id (int) player_id: the player_id of the captain (str) score: the score of the captains team (int) hr: a list of player's name who hit homeruns(List of str) ss: a list of player's name who hit sentry singles (List - str) Returns: status: 200 mimetype: application/json data: True """ unassigned_player = Player.query.filter_by( email=UNASSIGNED_EMAIL).first() unassigned_id = UNASSIGNED if unassigned_player is not None: unassigned_id = unassigned_player.id args = parser.parse_args() game_id = args['game_id'] game = Game.query.get(game_id) player_id = args['player_id'] captain = Player.query.get(player_id) if captain is None: raise PlayerNotSubscribed(payload={'details': player_id}) if game is None: raise GameDoesNotExist(payload={'details': game_id}) # find the team away_team = Team.query.get(game.away_team_id) home_team = Team.query.get(game.home_team_id) team = None if away_team.player_id == captain.id: team = away_team # captain of the squad elif home_team.player_id == captain.id: team = home_team # captain of the away squad else: # not a captain of a team raise NotTeamCaptain(payload={'details': kik}) homeruns = args['hr'] ss = args['ss'] score = args['score'] if score <= 0: # hmm that is so sad DB.session.add( Bat(unassigned_id, team.id, game.id, "fo", inning=1, rbi=0)) if homeruns is not None: for player_id in homeruns: # add the homeruns DB.session.add( Bat(player_id, team.id, game.id, "hr", inning=1, rbi=1)) score -= 1 if ss is not None: for player_id in ss: # add the special singles try: bat = Bat(player_id, team.id, game.id, "ss", inning=1, rbi=0) DB.session.add(bat) except InvalidField: pass if score < 0: raise InvalidField(payload={'details': "More hr than score"}) while score > 0: bat = Bat(unassigned_id, team.id, game.id, "s", inning=1, rbi=1) DB.session.add(bat) score -= 1 DB.session.commit() # good to add the submission return Response(dumps(True), status=200, mimetype="application/json")