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, 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 pull_schedule(year, league_id, page=1, page_size=PAGE_SIZE, url_route=None): """Pull the schedule for the given league and year""" team_mapper = get_team_map() if league_id not in get_league_map().keys(): raise LeagueDoesNotExist(payload={'details': league_id}) start = datetime.combine(date(year, 1, 1), time(0, 0)) end = datetime.combine(date(year, 12, 30), time(23, 0)) games = (Game.query.filter( and_(Game.league_id == league_id, Game.date.between(start, end)))).order_by("date").paginate( page, PAGE_SIZE, False) data = [] for game in games.items: result = game_to_json(game, team_mapper) if game.date.date() <= datetime.today().date(): scores = game.summary() result['score'] = (str(scores['home_score']) + '-' + str(scores['away_score'])) else: result['score'] = "" data.append(result) if url_route is None: url_route = (Routes['vschedule'] + "/" + str(year) + "/" + str(league_id)) return pagination_response_items(games, url_route, data)
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 put(self, league_id): """ PUT request for league Route: Route['league']/<league_id: int> Parameters : league_name: The league's name (string) Returns: if found and successful status: 200 mimetype: application/json data: None if found but not successful status: IFSC mimetype: application/json data: None otherwise status: 404 mimetype: application/json data: None """ # update a single user args = parser.parse_args() league = League.query.get(league_id) league_name = None if league is None: raise LeagueDoesNotExist(payload={'details': league_id}) if args['league_name']: league_name = args['league_name'] league.update(league_name) DB.session.commit() response = Response(dumps(None), status=200, mimetype="application/json") return response
def delete(self, league_id): """ DELETE request for League Route: Route['league']/<league_id: int> Returns: if found status: 200 mimetype: application/json data: None otherwise status: 404 mimetype: application/json data: None """ # delete a single user league = League.query.get(league_id) if league is None: raise LeagueDoesNotExist(payload={'details': league_id}) DB.session.delete(league) DB.session.commit() response = Response(dumps(None), status=200, mimetype="application/json") handle_table_change(Tables.LEAGUE, item=league.json()) return response
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 get_divisions_for_league_and_year(year, league_id): """Get a list of divisions that associated with the league for that year""" if get_league_map().get(league_id, None) is None: raise LeagueDoesNotExist(payload={'details': league_id}) start = datetime.combine(date(year, 1, 1), time(0, 0)) end = datetime.combine(date(year, 12, 30), time(23, 0)) division_ids = (DB.session.query( Division.id.distinct().label('id')).join(Game).filter( Game.league_id == league_id).filter(Game.date.between(start, end))).all() return [ Division.query.get(division[0]).json() for division in division_ids ]
def get(self, year, league_id): """ Get request for schedule data Route: Route['vschedule']/<int:year>/<int:team_id> Parameters: year: the year to get the schedule for league_id: the id of the league Returns: status: 200 mimetype: application/json data: [ { "away_team_id": int, "away_team": str, "date": str, "field": str, "home_team_id": int, "home_team": str, "league_id": int, "score": str(home team - away team), "status": str, "time": str } ] """ page = request.args.get('page', 1, type=int) g = (Game.query.filter) league = League.query.get(league_id) start = datetime.combine(date(year, 1, 1), time(0, 0)) end = datetime.combine(date(year, 12, 30), time(0, 0)) if league is None: raise LeagueDoesNotExist(payload={'details': league_id}) games = (Game.query.filter( and_(Game.league_id == league.id, Game.date.between(start, end)))).order_by("date").paginate( page, PAGE_SIZE, False) data = [] for game in games.items: result = game.json() if game.date < datetime.today(): scores = game.summary() result['score'] = (str(scores['home_score']) + '-' + str(scores['away_score'])) else: result['score'] = "" data.append(result) url_route = Routes['vschedule'] + "/" + str(year) + "/" + str( league_id) return pagination_response_items(games, url_route, data)
def get_league_id(self, league): ''' a method that gets the league id for the name Parameters: league: the league's name (str) Returns: id: the id of the team (int) None if no league is found ''' identification = None league = League.query.filter_by(name=league).first() if league is not None: identification = league.id else: # cant assume some league so return None s = "League does not exist: {}".format(league) raise LeagueDoesNotExist(payload={"details": s}) return identification
def set_teams(self): ''' a method that sets the teams for the league Parameters: None Updates: self.teams: a dictionary with {name:id, etc..} ''' self.teams = {} league = League.query.get(self.league_id) if league is None: raise LeagueDoesNotExist(payload={'details': league}) for team in league.teams: if team.year == self.year: self.teams[str(team)] = team.id sponsor = str(Sponsor.query.get(team.sponsor_id)) self.teams[sponsor + " " + team.color] = team.id
def get_team_lookup(league, year=datetime.datetime.today().year): ''' a method that sets the teams for the league Parameters: league: the json league object year: the year we are importing for Returns: teams: a dictionary object lookup for teams ''' teams = {} league = League.query.get(league["league_id"]) if league is None: raise LeagueDoesNotExist(payload={'details': league}) for team in league.teams: if team.year == year: teams[str(team)] = team.id sponsor = str(Sponsor.query.get(team.sponsor_id)) teams[sponsor + " " + team.color] = team.id return teams
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 get(self, league_id): """ GET request for League Object matching given league_id Route: Route['league']/<league_id: int> Returns: if found status: 200 mimetype: application/json data: {league_id:int, league_name:string} otherwise status: 404 mimetype: application/json data: None """ # expose a single League entry = League.query.get(league_id) if entry is None: raise LeagueDoesNotExist(payload={'details': league_id}) response = Response(dumps(entry.json()), status=200, mimetype="application/json") return response
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 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 sponsor model, team model, player model, league model """ for value in BACKGROUND.values(): if value not in background.keys(): errorMessage = MISSING_BACKGROUND.format(value) raise InvalidField(payload={"details": errorMessage}) league_name = background['league'] sponsor_name = background['sponsor'] team_color = background['color'] captain_name = background['captain'] if league_name.lower().startswith("ex."): error_message = LEFT_BACKGROUND_EXAMPLE.format(league_name) raise InvalidField(payload={"details": error_message}) elif sponsor_name.lower().startswith("ex."): error_message = LEFT_BACKGROUND_EXAMPLE.format(sponsor_name) raise InvalidField(payload={"details": error_message}) elif team_color.lower().startswith("ex."): error_message = LEFT_BACKGROUND_EXAMPLE.format(team_color) raise InvalidField(payload={"details": error_message}) elif captain_name.lower().startswith("ex."): error_message = LEFT_BACKGROUND_EXAMPLE.format(captain_name) raise InvalidField(payload={"details": error_message}) # nothing to do with the captain at this point captain = {"player_name": captain_name} # try to find sponsor and league sponsor = (Sponsor.query.filter( or_(func.lower(Sponsor.name) == func.lower(sponsor_name)), func.lower(Sponsor.nickname) == func.lower(sponsor_name))).first() league = League.query.filter( func.lower(League.name) == func.lower(league_name)).first() if sponsor is None: error_message = INVALID_SPONSOR.format(sponsor_name) raise SponsorDoesNotExist(payload={'details': error_message}) if league is None: error_message = INVALID_LEAGUE.format(league_name) raise LeagueDoesNotExist(payload={'details': error_message}) # check to see if team was already created teams = (Team.query.filter( func.lower(Team.color) == func.lower(team_color)).filter( Team.sponsor_id == sponsor.id).filter( Team.year == date.today().year)).all() if len(teams) > 0: team = teams[0].json() else: team = { 'team_id': None, "color": team_color, "sponsor_id": sponsor.id, "league_id": league.id, "captain": None, "year": date.today().year } return { "captain": captain, "team": team, "league": league.json(), "sponsor": sponsor.json() }