Example #1
0
class Fun(DB.Model):
    """
        A class used to store the amount of fun had by all.
        Columns:
            id: the unique id
            year: the year the fun count is for
            count: the total count for the year
    """
    id = DB.Column(DB.Integer, primary_key=True)
    year = DB.Column(DB.Integer)
    count = DB.Column(DB.Integer)

    def __init__(self, year=date.today().year, count=0):
        """ Fun constructor. """
        self.year = year
        self.count = count

    def update(self, count=None):
        """Update an existing fun count."""
        if count is not None:
            self.count = count

    def increment(self, change):
        """Increment the fun count.

        Parameters:
            change: the amount the fun count has changed by (int)
        """
        self.count += change

    def json(self):
        """Returns a jsonserializable object."""
        return {'year': self.year, 'count': self.count}
Example #2
0
    def setUp(self):
        self.show_results = False
        self.pp = PrettyPrinter(indent=4)
        self.db_fd, app.config['DATABASE'] = tempfile.mkstemp()
        self.d = "2014-8-23"
        self.t = "11:37"
        self.counter = 1
        app.config['TESTING'] = True
        self.app = app.test_client()
        self.to_delete = []
        self.bats_to_delete = []
        self.games_to_delete = []
        self.fun_to_delete = []
        self.espys_to_delete = []
        self.teams_to_delete = []
        self.players_to_delete = []
        self.sponsors_to_delete = []
        self.leagues_to_delete = []
        if (not self.tables_created()):

            DB.engine.execute('''
                                  DROP TABLE IF EXISTS fun;
                                  DROP TABLE IF EXISTS roster;
                                  DROP TABLE IF EXISTS bat;
                                  DROP TABLE IF EXISTS espys;
                                  DROP TABLE IF EXISTS game;
                                  DROP TABLE IF EXISTS team;
                                  DROP TABLE IF EXISTS player;
                                  DROP TABLE IF EXISTS sponsor;
                                  DROP TABLE IF EXISTS league;
                          ''')
            DB.create_all()
Example #3
0
class NumberCount(DB.Model):
    """ Model for storing number counts. """

    __tablename__ = "number_count"
    number = DB.Column(DB.Integer, primary_key=True)
    count = DB.Column(DB.Integer, nullable=False)

    def __repr__(self):
        """ Return str representation of NumberCount obj. """
        return f"<NumberCount {self.number}: {self.count}>"
Example #4
0
def app():
    """ Fixture for app initialized with test config. """
    db_fd, db_path = tempfile.mkstemp()

    app = create_app({
        "SQLALCHEMY_DATABASE_URI": f"sqlite:///{db_path}",
        "SQLALCHEMY_TRACK_MODIFICATIONS": False,
    })
    with app.app_context():
        DB.create_all()
    yield app

    os.close(db_fd)
    os.unlink(db_path)
Example #5
0
def create_fresh_tables():
    """Creates fresh tables and deletes any previous information."""
    # delete old information
    DB.session.commit()
    DB.engine.execute('''
                         DROP TABLE IF EXISTS fun;
                         DROP TABLE IF EXISTS roster;
                         DROP TABLE IF EXISTS bat;
                         DROP TABLE IF EXISTS espys;
                         DROP TABLE IF EXISTS game;
                         DROP TABLE IF EXISTS team;
                         DROP TABLE IF EXISTS player;
                         DROP TABLE IF EXISTS sponsor;
                         DROP TABLE IF EXISTS league;
                    ''')
    DB.create_all()
def create_fresh_tables():
    """Creates fresh tables and deletes any previous information."""
    # delete old information
    DB.session.commit()
    DB.engine.execute("DROP TABLE IF EXISTS join_league_request;")
    DB.engine.execute("DROP TABLE IF EXISTS flask_dance_oauth;")
    DB.engine.execute("DROP TABLE IF EXISTS fun;")
    DB.engine.execute("DROP TABLE IF EXISTS roster;")
    DB.engine.execute("DROP TABLE IF EXISTS bat;")
    DB.engine.execute("DROP TABLE IF EXISTS espys;")
    DB.engine.execute("DROP TABLE IF EXISTS game;")
    DB.engine.execute("DROP TABLE IF EXISTS division;")
    DB.engine.execute("DROP TABLE IF EXISTS team;")
    DB.engine.execute("DROP TABLE IF EXISTS player;")
    DB.engine.execute("DROP TABLE IF EXISTS sponsor;")
    DB.engine.execute("DROP TABLE IF EXISTS league;")
    DB.create_all()
Example #7
0
class League(DB.Model):
    """
    a class that holds all the information for a league.
    Columns:
        id: the league unique id
        name: the name of the league
        games: the games associated with the league
        teams: the teams part of the league
    """
    id = DB.Column(DB.Integer, primary_key=True)
    name = DB.Column(DB.String(120))
    games = DB.relationship('Game', backref='league', lazy='dynamic')
    teams = DB.relationship('Team', backref='league', lazy='dynamic')

    def __init__(self, name: str = None):
        """The constructor.

        Raises:
            InvalidField
        """
        if not string_validator(name):
            raise InvalidField(payload={'details': "League - name"})
        self.name = name

    def __repr__(self) -> str:
        """Returns the string representation of the League."""
        return self.name

    def json(self) -> dict:
        """Returns a jsonserializable object."""
        return {'league_id': self.id,
                'league_name': self.name}

    def update(self, league: str) -> dict:
        """Update an existing league.

        Raises:
            InvalidField
        """
        if not string_validator(league):
            raise InvalidField(payload={'details': "League - name"})
        self.name = league
Example #8
0
 def setUp(self):
     self.show_results = False
     self.pp = PrettyPrinter(indent=4)
     self.db_fd, app.config['DATABASE'] = tempfile.mkstemp()
     self.d = "2014-8-23"
     self.t = "11:37"
     app.config['TESTING'] = True
     self.app = app.test_client()
     DB.engine.execute('''   
                             DROP TABLE IF EXISTS fun;
                             DROP TABLE IF EXISTS roster;
                             DROP TABLE IF EXISTS bat;
                             DROP TABLE IF EXISTS espys;
                             DROP TABLE IF EXISTS game;
                             DROP TABLE IF EXISTS team;
                             DROP TABLE IF EXISTS player;
                             DROP TABLE IF EXISTS sponsor;
                             DROP TABLE IF EXISTS league;
                     ''')
     DB.create_all()
Example #9
0
class Division(DB.Model):
    """
    a class that holds all the information for a division in a eague.
    Columns:
        id: the division unique id
        name: the name of the division
        shortname: the short name of the division
        league: the league the division is part of
        games: the games that are part of division
    """
    id = DB.Column(DB.Integer, primary_key=True)
    name = DB.Column(DB.String(120))
    shortname = DB.Column(DB.String(120))
    games = DB.relationship('Game', backref='division', lazy='dynamic')

    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 get_shortname(self) -> str:
        """Returns the short name of the division"""
        if self.shortname is not None:
            return self.shortname
        return self.name

    def __repr__(self) -> str:
        """Returns the string representation of the League."""
        return self.name

    def json(self) -> dict:
        """Returns a jsonserializable object."""
        return {'division_id': self.id,
                'division_name': self.name,
                'division_shortname': self.shortname}
Example #10
0
class Espys(DB.Model):
    """
        A class that stores transaction for ESPY points.
        Columns:
            id: the unique id
            description: the description of the transaction (additional notes)
            sponsor_id: the id of sponsor that was involved in the transaction
            points: the amount of points awarded for the transaction ($1=1 pt)
            date: the date of the transaction
            receipt: any information regarding the receipt (receipt number)
    """
    id = DB.Column(DB.Integer, primary_key=True)
    team_id = DB.Column(DB.Integer, DB.ForeignKey('team.id'))
    description = DB.Column(DB.String(120))
    sponsor_id = DB.Column(DB.Integer, DB.ForeignKey('sponsor.id'))
    points = DB.Column(DB.Float)
    date = DB.Column(DB.DateTime)
    receipt = DB.Column(DB.String(30))

    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,
               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 json(self):
        """Returns a jsonserializable object."""
        sponsor = (None if self.sponsor_id is None else str(
            Sponsor.query.get(self.sponsor_id)))
        team = (None if self.team_id is None else str(
            Team.query.get(self.team_id)))
        date = None
        time = None
        if self.date is not None:
            date = self.date.strftime("%Y-%m-%d")
            time = self.date.strftime("%H:%M")
        return {
            'espy_id': self.id,
            'team': team,
            'team_id': self.team_id,
            'sponsor': sponsor,
            'sponsor_id': self.sponsor_id,
            'description': self.description,
            'points': self.points,
            'receipt': self.receipt,
            'date': date,
            'time': time
        }
Example #11
0
from api.model import Player, Team, Sponsor, Game, League, Bat, Espys, Fun
from random import randint
# delete old information
DB.session.commit()
DB.engine.execute('''   
                        DROP TABLE IF EXISTS fun;
                        DROP TABLE IF EXISTS roster;
                        DROP TABLE IF EXISTS bat;
                        DROP TABLE IF EXISTS espys;
                        DROP TABLE IF EXISTS game;
                        DROP TABLE IF EXISTS team;
                        DROP TABLE IF EXISTS player;
                        DROP TABLE IF EXISTS sponsor;
                        DROP TABLE IF EXISTS league;
                ''')
DB.create_all()
FUNS = {
       2002:89,
       2003: 100,
       2004: 177,
       2005:186,
       2006:176,
       2007: 254,
       2008: 290,
       2009: 342,
       2010: 304,
       2011: 377,
       2012: 377,
       2013: 461,
       2014: 349,
       2015: 501
Example #12
0
class Team(DB.Model):
    """
    A class that stores information about a team.
    Columns:
        id: the unique team id
        sponsor_id: the sposor id the team is associated with
        home_games: the home games of the team
        away_games: the away games of the team
        players: the players on the team's roster
        bats: the bats of the team
        league_id: the league id the team is part of
        year: the year the team played
        espys: the espy transaction that team has
    """
    id = DB.Column(DB.Integer, primary_key=True)
    color = DB.Column(DB.String(120))
    sponsor_id = DB.Column(DB.Integer, DB.ForeignKey('sponsor.id'))
    home_games = DB.relationship('Game',
                                 backref='home_team',
                                 lazy='dynamic',
                                 foreign_keys='[Game.home_team_id]')
    away_games = DB.relationship('Game',
                                 backref='away_team',
                                 lazy='dynamic',
                                 foreign_keys='[Game.away_team_id]')
    players = DB.relationship('Player',
                              secondary=roster,
                              backref=DB.backref('teams', lazy='dynamic'))
    bats = DB.relationship('Bat', backref='team', lazy='dynamic')
    league_id = DB.Column(DB.Integer, DB.ForeignKey('league.id'))
    year = DB.Column(DB.Integer)
    player_id = DB.Column(DB.Integer, DB.ForeignKey('player.id'))
    espys = DB.relationship('Espys', backref='team', lazy='dynamic')

    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 __repr__(self):
        """Returns the string representation."""
        result = []
        if self.sponsor_id is not None:
            sponsor = Sponsor.query.get(self.sponsor_id)
            if sponsor is not None and sponsor.nickname is not None:
                result.append(sponsor.nickname)
        if self.color is not None:
            result.append(self.color)
        return " ".join(result)

    def espys_awarded(self):
        """Returns the number of espy ponts the team has."""
        count = 0
        for espy in self.espys:
            count += espy.points
        return count

    def json(self):
        """Returns a jsonserializable object."""
        captain = (None if self.player_id is None else Player.query.get(
            self.player_id).json())
        return {
            'team_id': self.id,
            'team_name': str(self),
            'color': self.color,
            'sponsor_id': self.sponsor_id,
            'league_id': self.league_id,
            'year': self.year,
            'espys': self.espys_awarded(),
            'captain': captain
        }

    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 insert_player(self, player_id, captain=False):
        """Insert a player on to the team.

        Parameter:
            player_id: the id of the player to add
            captain: True if the player is the team's captain
        Returns:
            True if player was added
            False otherwise
        Raises:
            PlayerDoesNotExist
        """
        valid = False
        player = Player.query.get(player_id)
        if player is None:
            raise PlayerDoesNotExist(payload={'details': player_id})
        if captain:
            self.player_id = player_id
            if player not in self.players:
                self.players.append(player)
        else:
            if player not in self.players:
                self.players.append(player)
        return valid

    def remove_player(self, player_id):
        """Removes a player from a team.

        Parameter:
            player_id: the id of the player to remove
        Raises:
            MissingPlayer
        """
        player = Player.query.get(player_id)
        if player not in self.players:
            raise PlayerNotOnTeam(payload={'details': player_id})
        self.players.remove(player)

    def check_captain(self, player_name, password):
        """Checks if the player is the captain of the team.

        Parameters:
            player_name: the name of the player (str)
            password: the password of the player (str)
        Return:
            True of player is the captain
            False otherwise
        """
        player = Player.query.get(self.player_id)
        return player.name == player_name and player.check_password(password)

    def team_stats(self):
        pass
Example #13
0
class Sponsor(DB.Model):
    """
    A class that stores information about a sponsor.
    Columns:
        id: the sponsor's unique id
        name: the name of the sponsor
        teams: the teams the sponsor is associated with
        description: a description of the sponsor
        link: a link to the sponsor's website or facebook
        active: a boolean telling whether the sponsor
                is currently sponsoring a team
        espys: all the espys transaction associated with the sponsor
    """
    __tablename__ = 'sponsor'
    id = DB.Column(DB.Integer, primary_key=True)
    name = DB.Column(DB.String(120), unique=True)
    teams = DB.relationship('Team', backref='sponsor', lazy='dynamic')
    description = DB.Column(DB.String(200))
    link = DB.Column(DB.String(100))
    active = DB.Column(DB.Boolean)
    espys = DB.relationship('Espys', backref='sponsor', lazy='dynamic')
    nickname = DB.Column(DB.String(100))

    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 __repr__(self):
        """Returns the string representation of the sponsor."""
        return self.name if self.name is not None else ""

    def json(self):
        """Returns a jsonserializable object."""
        return {
            'sponsor_id': self.id,
            'sponsor_name': self.name,
            'link': self.link,
            'description': self.description,
            'active': self.active
        }

    def update(self, name=None, link=None, description=None, active=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 activate(self):
        """Activate a sponsor (they are back baby)."""
        self.active = True

    def deactivate(self):
        """Deactivate a sponsor (they are no longer sponsoring). """
        self.active = False
Example #14
0
class Player(DB.Model):
    """
    A class that stores a player's information.
        id: the player's unique id
        name: the name of the player
        email: the unique player's email
        gender: the player's gender
        password: the password for the player
        team: the teams the player plays for
        active: a boolean to say whether the player is active
                currently or not (retired or not)
        kik: the kik user name associated with the player
    """
    id = DB.Column(DB.Integer, primary_key=True)
    name = DB.Column(DB.String(80))
    email = DB.Column(DB.String(120), unique=True)
    gender = DB.Column(DB.String(1))
    password = DB.Column(DB.String(120))
    bats = DB.relationship('Bat', backref='player', lazy='dynamic')
    team = DB.relationship('Team', backref='player', lazy='dynamic')
    active = DB.Column(DB.Boolean)
    kik = DB.Column(DB.String(120))

    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 set_password(self, password):
        """Update a player's password.

            Parameters:
                password: the player's new password (str)
        """
        self.password = generate_password_hash(password)

    def check_password(self, password):
        """Check a player's password.

            Parameters:
                password: attempted password (str)
            Returns:
                True passwords match
                False otherwise
        """
        return check_password_hash(self.password, password)

    def __repr__(self):
        """Return the string representation of the player."""
        return self.name + " email:" + self.email

    def update_kik(self, kik):
        """Update the player's kik profile."""
        self.kik = kik

    def json(self):
        """Returns a jsonserializable object."""
        return {
            "player_id": self.id,
            "player_name": self.name,
            "gender": self.gender,
            "active": self.active
        }

    def admin_json(self):
        """Returns a jsonserializable object."""
        return {
            "player_id": self.id,
            "player_name": self.name,
            "gender": self.gender,
            "email": self.email,
            "active": self.active
        }

    def update(self,
               name=None,
               email=None,
               gender=None,
               password=None,
               active=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")
            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 activate(self):
        """Activate the player."""
        self.active = True

    def deactivate(self):
        """Deactivate the player (retire them)."""
        self.active = False
class Listing(DB.Model):
    """
        Database table for listings.
    """
    id = DB.Column(DB.Integer, primary_key=True, autoincrement=True)
    neighborhood = DB.Column(DB.Unicode(30), nullable=False)
    room_type = DB.Column(DB.Unicode(20), nullable=False)
    min_nights = DB.Column(DB.Integer, nullable=True)
    num_reviews = DB.Column(DB.Integer, nullable=True)
    listings_count = DB.Column(DB.Integer, nullable=True)
    availability_365 = DB.Column(DB.Integer, nullable=True)
    last_review = DB.Column(DB.Integer, nullable=True)
    price = DB.Column(DB.Float, nullable=False)
    time = DB.Column(DB.DateTime,
                     nullable=False,
                     default=datetime.datetime.utcnow)
Example #16
0
"""
from api import DB
from sqlalchemy import func
from werkzeug.security import generate_password_hash, check_password_hash
from datetime import date, datetime, time
from api.variables import HITS, KIKPOINTS
from api.errors import TeamDoesNotExist, PlayerDoesNotExist, GameDoesNotExist,\
                        InvalidField, LeagueDoesNotExist, SponsorDoesNotExist,\
                        NonUniqueEmail, PlayerNotOnTeam, PlayerNotSubscribed,\
                        BadRequestError
from api.validators import rbi_validator, hit_validator, inning_validator,\
                           string_validator, date_validator, time_validator,\
                           field_validator, year_validator, gender_validator,\
                           float_validator, boolean_validator
roster = DB.Table(
    'roster', DB.Column('player_id', DB.Integer, DB.ForeignKey('player.id')),
    DB.Column('team_id', DB.Integer, DB.ForeignKey('team.id')))
SUBSCRIBED = "{} SUBSCRIBED"
AWARD_POINTS = "{} awarded espy points for subscribing: {}"


class Fun(DB.Model):
    """
        A class used to store the amount of fun had by all.
        Columns:
            id: the unique id
            year: the year the fun count is for
            count: the total count for the year
    """
    id = DB.Column(DB.Integer, primary_key=True)
    year = DB.Column(DB.Integer)
Example #17
0
from api import DB

DB.create()
Example #18
0
class JoinLeagueRequest(DB.Model):
    """
        A class used to store requests to join a league.
        Columns:
            team_id: the team they want to join
            name: the name they want to use
            email: the email from the Oauth provider
            pending: whether waiting for the outcome of the request
    """
    id = DB.Column(DB.Integer, primary_key=True)
    team_id = DB.Column(DB.Integer, DB.ForeignKey(Team.id), nullable=False)
    team = DB.relationship(Team)
    email = DB.Column(DB.String(120), nullable=False)
    name = DB.Column(DB.String(120), nullable=False)
    pending = DB.Column(DB.Boolean)
    gender = DB.Column(DB.String(1))

    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 accept_request(self) -> 'Player':
        """Accept the request and add the player to the team"""
        # create a player if they do not exit already
        if not self.pending:
            raise HaveLeagueRequestException("Request already submitted")
        player = Player.query.filter(
            func.lower(Player.email) == self.email.lower()).first()
        if player is None:
            player = Player(self.name, self.email, gender=self.gender)
            DB.session.add(player)
            DB.session.commit()
        self.pending = False
        team = Team.query.get(self.team_id)
        team.insert_player(player.id)
        DB.session.commit()
        return player

    def decline_request(self) -> None:
        """Decline the request."""
        self.pending = False
        DB.session.commit()

    def json(self) -> dict:
        """Get a json version of the model"""
        team = (None if self.team_id is None
                else Team.query.get(self.team_id).json())
        return {
            "team": team,
            "email": self.email,
            "id": self.id,
            "pending": self.pending,
            "player_name": self.name,
            "gender": self.gender
        }
Example #19
0
class Team(DB.Model):
    """
    A class that stores information about a team.
    Columns:
        id: the unique team id
        sponsor_id: the sposor id the team is associated with
        home_games: the home games of the team
        away_games: the away games of the team
        players: the players on the team's roster
        bats: the bats of the team
        league_id: the league id the team is part of
        year: the year the team played
        espys: the espy transaction that team has
    """
    id = DB.Column(DB.Integer, primary_key=True)
    color = DB.Column(DB.String(120))
    sponsor_id = DB.Column(DB.Integer, DB.ForeignKey('sponsor.id'))
    home_games = DB.relationship('Game',
                                 backref='home_team',
                                 lazy='dynamic',
                                 foreign_keys='[Game.home_team_id]')
    away_games = DB.relationship('Game',
                                 backref='away_team',
                                 lazy='dynamic',
                                 foreign_keys='[Game.away_team_id]')
    players = DB.relationship('Player',
                              secondary=roster,
                              backref=DB.backref('teams', lazy='dynamic'))
    bats = DB.relationship('Bat',
                           backref='team',
                           lazy='dynamic')
    league_id = DB.Column(DB.Integer, DB.ForeignKey('league.id'))
    year = DB.Column(DB.Integer)
    player_id = DB.Column(DB.Integer, DB.ForeignKey('player.id'))
    espys = DB.relationship('Espys',
                            backref='team',
                            lazy='dynamic')
    espys_total = column_property(select([func.sum(Espys.points)]).where(
        Espys.team_id == id).correlate_except(Espys), deferred=True)
    sponsor_name = column_property(select([Sponsor.nickname]).where(
        Sponsor.id == sponsor_id).correlate_except(Sponsor))

    def __init__(self,
                 color: str = None,
                 sponsor_id: int = None,
                 league_id: int = None,
                 year: int = 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 __repr__(self) -> str:
        """Returns the string representation."""
        if self.sponsor_name is not None and self.color is not None:
            return f"{self.sponsor_name} {self.color}"
        elif self.sponsor_name is not None:
            return f"{self.sponsor_name}"
        elif self.color is not None:
            return f"{self.color}"
        else:
            return f"Team: {self.id}"

    def json(self, admin: bool = False) -> dict:
        """Returns a jsonserializable object."""
        if admin:
            captain = (None if self.player_id is None
                       else Player.query.get(self.player_id).admin_json())
        else:
            captain = (None if self.player_id is None
                       else Player.query.get(self.player_id).json())
        return {
            'team_id': self.id,
            'team_name': str(self),
            'color': self.color,
            'sponsor_id': self.sponsor_id,
            'league_id': self.league_id,
            'year': self.year,
            'espys': self.espys_total if self.espys_total is not None else 0,
            'captain': captain}

    def update(self,
               color: str = None,
               sponsor_id: int = None,
               league_id: int = None,
               year: int = None) -> 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 insert_player(self, player_id: int, captain: bool = False) -> None:
        """Insert a player on to the team.

        Parameter:
            player_id: the id of the player to add
            captain: True if the player is the team's captain
        Returns:
            True if player was added
            False otherwise
        Raises:
            PlayerDoesNotExist
        """
        valid = False
        player = Player.query.get(player_id)
        if player is None:
            raise PlayerDoesNotExist(payload={'details': player_id})
        if not self.is_player_on_team(player):
            self.players.append(player)
            valid = True
        if captain:
            self.player_id = player_id
            valid = True
        return valid

    def remove_player(self, player_id: int) -> None:
        """Removes a player from a team.

        Parameter:
            player_id: the id of the player to remove
        Raises:
            MissingPlayer
        """
        player = Player.query.get(player_id)
        if not self.is_player_on_team(player):
            raise PlayerNotOnTeam(payload={'details': player_id})
        self.players.remove(player)

    def is_player_on_team(self, player: 'Player') -> bool:
        """Returns whether the given player is on the team

        Parameter:
            player: the player model
        Returns:
            True if player on team otherwise False (boolean)
        """
        if player is None:
            return False
        return player.id in [p.id for p in self.players]

    def check_captain(self, player_name: str, password: str) -> str:
        """Checks if the player is the captain of the team.

        Parameters:
            player_name: the name of the player (str)
            password: the password of the player (str)
        Return:
            True of player is the captain
            False otherwise
        """
        player = Player.query.get(self.player_id)
        return player.name == player_name and player.check_password(password)

    def team_stats(self) -> None:
        pass
Example #20
0
class OAuth(OAuthConsumerMixin, DB.Model):
    """A model for storing information about oauth"""
    provider_user_id = DB.Column(DB.String(256), unique=True, nullable=False)
    player_id = DB.Column(DB.Integer, DB.ForeignKey(Player.id), nullable=False)
    player = DB.relationship(Player)