Пример #1
0
    def setUp(self):
        super().setUp()

        self.mitch = AppUser(phone_number=self.inviter_number,
                             username='******',
                             timezone=US_TIMEZONES['b'])
        self.db.session.add(self.mitch)

        self.billy = AppUser(phone_number=self.secondary_number,
                             username='******',
                             timezone=US_TIMEZONES['b'])
        self.db.session.add(self.billy)

        self.team = Team(founder=self.mitch, name='The Cherrys')
        self.db.session.add(self.team)

        self.mitch_member = TeamMember(user=self.mitch,
                                       team=self.team,
                                       inviter=self.mitch,
                                       status=Statuses.ACTIVE)
        self.db.session.add(self.mitch_member)

        self.billy_member = TeamMember(user=self.billy,
                                       team=self.team,
                                       inviter=self.mitch,
                                       status=Statuses.PENDING)
        self.db.session.add(self.billy_member)

        self.db.session.commit()

        self.mitch = self.mitch.to_dict()
        self.billy = self.billy.to_dict()
        self.team = self.team.to_dict()
Пример #2
0
def seed_teams():
    user = User.query.filter(User.username == "Demo").first()
    data = [Team(teamName="Gold"), Team(teamName="Green")]
    for team in data:
        user.teams.append(team)
        db.session.add(team)
    db.session.commit()
Пример #3
0
 def team_match_storage(self, data):
     for d in data:
         group = Group.query.filter_by(name=d["group_name"]).first()
         if group is None:
             group = Group(name=d["group_name"])
             db.session.add(group)
         v1 = Team.query.filter_by(name=d["v1"]).first()
         if v1 is None:
             v1 = Team(name=d["v1"], group=group)
             v1_pinyin = TeamPinYin(name=pinyin.get(d["v1"],
                                                    format="strip"),
                                    team=v1)
             db.session.add(v1)
             db.session.add(v1_pinyin)
         v2 = Team.query.filter_by(name=d["v2"]).first()
         if v2 is None:
             v2 = Team(name=d["v2"], group=group)
             v2_pinyin = TeamPinYin(name=pinyin.get(d["v2"],
                                                    format="strip"),
                                    team=v2)
             db.session.add(v2)
             db.session.add(v2_pinyin)
         db.session.commit()
         duel = Duel(team_er=v1,
                     team_ed=v2,
                     t1_score=d["vs"][0],
                     t2_score=d["vs"][2],
                     datetime=d["datetime"],
                     area=d["area"],
                     group_cls=d["group_cls"])
         db.session.add(duel)
         db.session.commit()
         print("保存%s小组赛成功..." % d["group_name"])
Пример #4
0
def seed_teams():

    team1 = Team(name="Water-Team", user_id="1")
    team2 = Team(name="Fire-Team", user_id="1")

    db.session.add(team1)
    db.session.add(team2)

    db.session.commit()
Пример #5
0
    def setUp(self):
        super().setUp()
        # add a user
        self.mitch = AppUser(phone_number=self.inviter_number,
                             username='******',
                             timezone=US_TIMEZONES['b'])

        self.db.session.add(self.mitch)
        # self.db.session.add(self.blair)

        # add a notif
        self.notif = Notification(router=RouterNames.DID_YOU_DO_IT,
                                  hour=21,
                                  minute=0,
                                  active=True,
                                  user=self.mitch)

        self.db.session.add(self.notif)

        # add exchange
        self.exchange = Exchange(router=RouterNames.DID_YOU_DO_IT,
                                 outbound='Did you do it?',
                                 user=self.mitch,
                                 created=dt.datetime.now() -
                                 dt.timedelta(days=10))

        self.db.session.add(self.exchange)

        # add point
        self.point = Point(value=10, user=self.mitch)

        # add task
        self.task = Task(description='Win today',
                         due_date=dt.datetime.now(),
                         active=True,
                         exchange=self.exchange,
                         user=self.mitch)

        self.db.session.add(self.task)

        self.inteam = Team(id=TEST_TEAM_ID, founder=self.mitch, name='inteam')
        self.db.session.add(self.inteam)

        self.pendingteam = Team(founder=self.mitch, name='pendingteam')
        self.db.session.add(self.pendingteam)

        self.mitch_member = TeamMember(user=self.mitch,
                                       team=self.inteam,
                                       inviter=self.mitch,
                                       status=Statuses.ACTIVE)
        self.db.session.add(self.mitch_member)

        self.mitch_member2 = TeamMember(user=self.mitch,
                                        team=self.pendingteam,
                                        inviter=self.mitch,
                                        status=Statuses.PENDING)
        self.db.session.add(self.mitch_member2)
Пример #6
0
def seed_teams():

    team1 = Team(name='Valor')
    team2 = Team(name='Mystic')
    team3 = Team(name='Instinct')

    db.session.add(team1)
    db.session.add(team2)
    db.session.add(team3)

    db.session.commit()
Пример #7
0
 def test_team(self):
     team1 = Team(name='Yankees', city='New York', abbreviation='NYY')
     team2 = Team(name='Cubs', city='Chicago', abbreviation='CHC')
     db.session.add(team1)
     db.session.add(team2)
     db.session.commit()
     self.assertEqual(team1.name, 'Yankees')
     self.assertEqual(team1.city, 'New York')
     self.assertEqual(team1.abbreviation, 'NYY')
     self.assertEqual(team2.name, 'Cubs')
     self.assertEqual(team2.city, 'Chicago')
     self.assertEqual(team2.abbreviation, 'CHC')
Пример #8
0
def deploy():
    """Deployment tasks"""
    #migrate database to latest revision
    upgrade()
    #create user roles
    Role.insert_roles()
    #insert matches from the data file
    Team.insert_teams()
    #insert modules
    PredictionModule.insert_modules()
    #insert matches from the data file
    Match.update_all_matches()
Пример #9
0
def teams_post(id):
    form = TeamForm()
    user = User.query.get(id)
    form['csrf_token'].data = request.cookies['csrf_token']
    if form.validate_on_submit():
        team = Team(
            teamName=form.data['teamName'],
        )
        team.users.append(user)
        db.session.add(team)
        db.session.commit()
        return team.to_dict()
    return "Oops, something went wrong!"
Пример #10
0
    def setUpTestData(cls):
        admin = Group(name='Admin')
        admin.save()
        coach = Group(name='Coach')
        coach.save()
        player = Group(name='Player')
        player.save()
        admin_user = User.objects.create_user(username='******', email='*****@*****.**', is_staff=True,
                                              password='******')
        admin.user_set.add(admin_user)

        cls.colombo_fc_user1 = User.objects.create_user(username='******', email='*****@*****.**',
                                                        password='******')
        player.user_set.add(cls.colombo_fc_user1)
        cls.colombo_fc_user2 = User.objects.create_user(username='******', email='*****@*****.**',
                                                        password='******')
        player.user_set.add(cls.colombo_fc_user2)
        cls.navy_sc_user1 = User.objects.create_user(username='******', email='*****@*****.**',
                                                     password='******')
        player.user_set.add(cls.navy_sc_user1)
        cls.navy_sc_user2 = User.objects.create_user(username='******', email='*****@*****.**',
                                                     password='******')
        player.user_set.add(cls.navy_sc_user2)

        cls.first_round = GameRound(name='First Round')
        cls.first_round.save()
        quarter_final = GameRound(name='Quarter Final')
        quarter_final.save()
        semi_final = GameRound(name='Semi Final')
        semi_final.save()
        final = GameRound(name='Final')
        final.save()
        cls.colombo_fc = Team(name='Colombo FC')
        cls.colombo_fc.save()
        cls.navy_sc = Team(name='Navy SC')
        cls.navy_sc.save()

        cls.game = Game(host=cls.navy_sc, guest=cls.colombo_fc, winner=cls.navy_sc, round=cls.first_round
                        , date='2020-12-23')
        cls.game.save()

        cls.navy_sc_player = Player(user=cls.navy_sc_user1, team=cls.navy_sc, height=179)
        cls.navy_sc_player.save()
        cls.player_stat = PlayerStat(player=cls.navy_sc_player, game=cls.game, score=1)
        cls.player_stat.save()
        cls.team_stat = TeamStat(team=cls.navy_sc, game=cls.game, score=1)
        cls.team_stat.save()

        cls.site_stat = SiteStat(user=cls.navy_sc_user1, login_time='2021-02-15T04:25:37+05:30',
                                 logout_time='2021-02-15T16:59:16+05:30')
        cls.site_stat.save()
Пример #11
0
def add_team():
    form = TeamForm(request.form)

    if form.validate_on_submit():
        team = Team()
        team.fio = form.fio.data
        file = request.files['avatar']
        filename = secure_filename(file.filename)
        file.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))
        team.avatar = filename
        db.session.add(team)
        db.session.commit()
        return redirect('/')
    return render_template('add_team.html', form=form)
Пример #12
0
def add_team(request):
    if not request.user.is_staff:
        raise Http404

    if request.POST.get('teamName'):
        teamName = request.POST.get('teamName')
        teamStructure = request.POST.get('teamStructure')
        teamGame = Game.objects.get(pk=request.POST.get('teamGame'))
        team = Team(name=teamName, structure=teamStructure, game=teamGame)
        team.save()
    else:
        print("error: Team was not created")

    return redirect('/admin')
Пример #13
0
def team(request):
    """
    """
    if request.method == 'POST':
        team_name = request.POST.get('teamname', False)
        if team_name:
            new_team = Team()
            new_team.team_name = team_name
            new_team.save()
            return HttpResponseRedirect(reverse('players', args=(new_team.id,)))
        else:
            return render(request, 'app/add_team.html')
    else:
        return render(request, 'app/add_team.html')
def team(client, app):
    with app.app_context():
        db.session.add(Team(id=1, name='Test Team', status='completed'))

        db.session.commit()

        yield db.session.query(Team).all()
def create_team():
    user = users.get(current_user.id)
    created_teams = team_service.get_teams_for_user(user.id, 'created')
    completed_teams = team_service.get_teams_for_user(user.id)

    if len(completed_teams) == 0:
        if len(created_teams) == 0:
            team = team_service.save(
                Team(name='',
                     status='created',
                     team_members=[
                         TeamMember(user_id=user.id, is_team_lead=True)
                     ]))

            audit_service.log_audit_event(audit_type=audit_types.create_team,
                                          data={},
                                          db_object=team,
                                          user=current_user.email_address)

            publish_tasks.team.delay(publish_tasks.compress_team(team),
                                     'created')

            return get_team(team.id)

        created_team = created_teams.pop()
        return get_team(created_team.id)
    else:
        team = completed_teams[0]
        raise TeamError(
            'You can only be in one team. You\'re already a member of {}.'.
            format(team.name))
Пример #16
0
def join_team(account, teamID=None, teamPass=None, team=None):

    # Look up the team if we didn't bring one
    if team is None:
        team = Team.objects(teamID=teamID, teamPass=teamPass).first()

    # We didn't bring a team nor did we find one
    if team is None:
        error = "Team with those credentials not found."

    # We have our team, let's try joining
    if team:
        if len(team.members) < 3:
            team.members.append(account)
            account.team = team
            validate_division(team)
            team.save()
            account.save()
            return True
        else:
            flash("Team already has 3 members", 'danger')
            return False

    flash("Error finding team", 'danger')
    return False
Пример #17
0
def test_can_create_table_entry_from_api_response():
    table_entry = TableEntry.parse_obj({
        "position": 2,
        "team": {
            "id": 65,
            "name": "Manchester City FC",
            "crestUrl": "https://upload.wikimedia.org/wikipedia/en/e/eb/Manchester_City_FC_badge.svg"
        },
        "playedGames": 31,
        "won": 20,
        "draw": 3,
        "lost": 8,
        "points": 63,
        "goalsFor": 77,
        "goalsAgainst": 33,
        "goalDifference": 44
    })

    assert table_entry.position == 2
    assert table_entry.team == Team(id=65, name='Manchester City FC')
    assert table_entry.played_games == 31
    assert table_entry.won == 20
    assert table_entry.draw == 3
    assert table_entry.lost == 8
    assert table_entry.goals_for == 77
    assert table_entry.goals_against == 33
    assert table_entry.goal_difference == 44
Пример #18
0
def _create_team(request):
    team = Team()
    form = TeamForm(request.form)
    form.populate_obj(team)
    db.session.add(team)
    db.session.commit()
    return team
Пример #19
0
def changeActivitiesProcess():
    teams = current_user.entry.teams.count()
    activities = form_input_array(request.form, "activity")

    # TODO: sort cascades properly (can't test on SQLite)
    for team in current_user.entry.teams:
        team.clearScores()

    current_user.entry.teams.delete()
    current_user.entry.activities.delete()
    db.session.commit()

    if len(activities) != 4:
        flash("Please select four activities", "warning")
        return redirect(url_for("scoring.changeActivities"))

    for activity in activities:
        obj = Activity.query.get(activity[1])
        if obj:
            current_user.entry.activities.append(EntryActivities(activity=obj))
        else:
            flash("Please select a valid activity", "warning")
            return redirect(url_for("scoring.changeActivities"))

    for team in range(1, teams + 1):
        current_user.entry.teams.append(Team())

    db.session.commit()

    return redirect(url_for("scoring.index"))
Пример #20
0
def create_team(game_id):
    form = CreateTeamForm()

    existing_player_team = PlayerTeam.query.join(Team).filter(
        PlayerTeam.player_id == g.current_player.id, Team.game_id == game_id).one_or_none()

    if existing_player_team:
        form.autojoin_team.data = False
        form.autojoin_team.render_kw = {'disabled':''}


    if form.validate_on_submit(): # make sure game is open, stuff like that, user is logged in, user isnt already in game
        new_team = Team(name=form.name.data, game_id=game_id)
        db.session.add(new_team)
        db.session.flush()

        if form.autojoin_team.data:
            player_team = PlayerTeam(player_id=g.current_player.id, team_id=new_team.id)
            db.session.add(player_team)
        db.session.commit()

        return True, redirect(url_for('.view_game', game_id=game_id))

    return False, render_template(
        'salad_bowl/actions/create_team.html',
        form=form,
        action_url=url_for('salad_bowl.create_team', game_id=game_id))
Пример #21
0
def flumride_set_has_payed(id):
    team = Team.get(id)
    team.has_payed = True
    db.session.commit()
    resp = jsonify(has_payed=True)
    resp.status_code = 200
    return resp
Пример #22
0
def manageteam(id):
    project = Project.query.filter_by(id=id).first_or_404()
    form = TeamForm()
    team = Team.query.filter_by(project_id=int(id)).order_by(
        Team.role.asc()).all()
    if form.validate_on_submit():
        member = Team(role=form.role.data,
                      firstname=form.fName.data,
                      lastname=form.lName.data,
                      email=form.email.data,
                      project_id=project.id)
        exists = Team.query.filter_by(project_id=int(id),
                                      role=form.role.data).first()
        if not exists:
            db.session.add(member)
            db.session.commit()
            flash('Team Member {} {} added'.format(form.fName.data,
                                                   form.lName.data))
        else:
            db.session.commit()
            flash('Team Member {} {} updated'.format(form.fName.data,
                                                     form.lName.data))
        return redirect(url_for('manageteam', id=project.id))
    return render_template('manageteam.html',
                           title='Manage Team Members',
                           team=team,
                           form=form,
                           project=project)
Пример #23
0
def join_to_event(current_user, event_id):
    team_id = request.args.get('teamId', None, type=int)

    try:
        int(event_id)
    except ValueError:
        return response('failed', 'Please provide a valid Event Id', 400)

    user = User.get_by_id(current_user.id)
    event = Event.get_by_id(event_id)
    if not event:
        abort(404)

    if event == EventStatus.canceled:
        return response('failed', 'Event was canceled', 400)

    if event == EventStatus.ended:
        return response('failed', 'Event was ended', 400)

    if team_id:
        team = Team.get_by_id(team_id)

        if not team:
            return response('failed', 'Team cannot be found', 404)

        if not team in event.teams:
            return response(
                'failed', 'The Event with Id ' + event_id +
                ' doesn\'t have Team with Id ' + team_id, 404)

    elif event.type is EventType.training:
        team = event.training.team
    else:
        return response('failed',
                        'Event with given Id requires teamId to join', 404)

    #check requirements to join
    if not (event.participants_age_from <= user.age <=
            event.participants_age_to):
        return response(
            'failed', 'User\'s age does\'t meet the requirements of the event',
            400)

    if user in team.participants:
        return response('failed', 'User already joined to the team', 400)

    if team.is_full:
        return response('failed', 'Team is full', 400)

    # remove user from other team in event
    for t in event.teams:
        if user in t.participants:
            t.participants.remove(user)

    # add user to team
    team.participants.append(user)
    team.update()

    return response_for_created_event(event.json(current_user), 201)
Пример #24
0
def teams(app):
    with app.app_context():
        db.session.add(
            Team(id=1,
                 name='Marketplace',
                 email_address='*****@*****.**',
                 status='completed'))

        db.session.add(
            Team(id=2,
                 name='Cloud',
                 email_address='*****@*****.**',
                 status='completed'))

        db.session.commit()

        yield db.session.query(Team).all()
Пример #25
0
def register():
    if current_user.is_authenticated:
        return redirect(url_for('index'))
    form = RegistrationForm()
    if form.validate_on_submit():
        team = Team(username=form.username.data,
                    team_name=form.team_name.data,
                    trainer=form.trainer.data,
                    trainer_email=form.trainer_email.data,
                    team_size=form.team_size.data,
                    athlete_userids=form.athlete_userids.data)
        team.set_password(form.password.data)
        db.session.add(team)
        db.session.commit()
        flash('Congratulations, your team is now registered!')
        return redirect(url_for('login'))
    return render_template('register.html', title='Register', form=form)
Пример #26
0
    def test_team_fails_validation_with_bad_email_address(
            self, users, user, email_address):
        team = Team(name='Marketplace', email_address=email_address)

        errors = TeamValidator(team, user).validate_basics()

        assert len(errors) >= 1
        assert any(error['id'] == 'T002' for error in errors)
    def test_team_passes_validation_with_name_and_email(self, users, user):
        team = Team(email_address='*****@*****.**',
                    name='Marketplace')

        errors = TeamValidator(team, user,
                               ['teamtest.gov.au']).validate_basics()

        assert len(errors) == 0
Пример #28
0
    def test_team_fails_validation_when_email_domain_is_different_to_user_domain(
            self, users, user):
        team = Team(name='Marketplace',
                    email_address='*****@*****.**')

        errors = TeamValidator(team, user).validate_basics()

        assert len(errors) == 1
        assert any(error['id'] == 'T003' for error in errors)
Пример #29
0
 def test_show_teams_api(self):
     team = Team(name='cricket', logouri=IMAGE)
     db.session.add(team)
     db.session.commit()
     url = 'http://localhost:5000/teams'
     teams = self.app.get(url).data
     teams = json.loads(teams)['teams']
     self.assertEquals(len(teams), 1)
     self.assertEquals(teams[0]['name'], 'cricket')
Пример #30
0
 def test_add_high5s(self):
     new_user = User(user_name='Jimmy',
                     name='Jimmy John',
                     email='*****@*****.**',
                     password='******')
     app_db.session.add(new_user)
     app_db.session.commit()
     new_team = Team(name="Men's Running Club Test", admin="Jimmy")
     team_members = []
     team_members.append("John")
     team_members.append("Tom")
     list(set(team_members))
     for team_member in team_members:
         user1 = User.query.filter(User.user_name == team_member).one()
         if user1:
             new_team.members.append(user1)
     app_db.session.add(new_team)
     high5_1 = High5(
         receiver='Tom',
         giver='Jimmy',
         message=
         'Tom went in to extra office hours to get feedback on our project change idea',
         time_posted=datetime.datetime.utcnow(),
         level=5,
         team=new_team)
     high5_2 = High5(
         receiver='John',
         giver='Tom',
         message=
         'John went to the store to get supplies to make paper prototypes.',
         time_posted=datetime.datetime.utcnow(),
         level=4,
         team=new_team)
     app_db.session.add(high5_1)
     app_db.session.add(high5_2)
     app_db.session.commit()
     high5s = High5.query.filter(
         High5.team_name == "Men's Running Club Test").all()
     self.assertEqual(len(high5s), 2)
     john = User.query.filter(User.user_name == "John").one()
     new_team.members.remove(john)
     High5.query.filter(
         High5.team_name == "Men's Running Club Test").filter(
             High5.receiver == "John").delete()
     app_db.session.commit()
     high5s = High5.query.filter(
         High5.team_name == "Men's Running Club Test").all()
     self.assertEqual(len(high5s), 1)
     app_db.session.delete(new_team)
     app_db.session.delete(new_user)
     app_db.session.commit()
     team_exists = Team.query.filter(
         Team.name == "Men's Running Club Test").all()
     self.assertEqual(len(team_exists), 0)
     high5s = High5.query.filter(
         High5.team_name == "Men's Running Club Test").all()
     self.assertEqual(len(high5s), 0)
Пример #31
0
def register_league(league):
    form = LeagueRegistrationForm()
    league = League.query.filter_by(id=int(league)).first()
    teams = current_user.get_teams()
    if teams is not None:
        form.teams.choices = [(team.id, "{}".format(team.name))
                              for team in teams]
    if request.method == 'POST':
        if form.new_team.data:
            # create a new team
            team = Team.query.filter_by(name=form.new_team.data).first()
            if team is not None and team.account_id == current_user.id:
                flash(
                    'The team already exists, please select the team in the menu or create a team with another name!'
                )
                return redirect(url_for('register_league', league=league.id))
            else:
                team = Team(name=form.new_team.data, account=current_user)
                db.session.add(team)
        else:
            team_id = form.teams.data
            team = Team.query.filter_by(id=team_id).first()
        if team.has_registered(league):
            flash('The team has already registered the league!')
            return redirect(url_for('index'))
        elif league.registrable():
            league_team = League_Team(
                league_id=league.id,
                team_id=team.id,
                scheduling_requests=form.scheduling_requests.data)
            league.team_num = league.team_num + 1
            league_team.league = league
            league_team.team = team
            db.session.add(league_team)
            db.session.commit()
            send_confirmation_email(current_user, team, league)
            flash('The member has successfully registered the event!')
            return redirect(url_for('index'))
        else:
            flash(
                'There registration is up to limit, contact us for further info!'
            )
            return redirect(url_for('index'))
    return render_template('league_register.html', form=form)
Пример #32
0
def check_sched_loaded(Team, messages, err):
    print("check_sched")
    messages.append("Checking to see if schedule is loaded for " + Team.name)

    if not Team.is_pst_sched_loaded():
        messages.append("Schedule not loaded, getting it now")
        count = get_games(Team, messages, err)
        if count:
            return count
    else:
        messages.append("Schedule is already loaded")
Пример #33
0
def populate():
    Position.insert_positions()

    with app.open_resource('./testing/data/teams.json') as teamdata:
        team_dict = json.load(teamdata)['teams']
        team_models = []
        for t in team_dict:
            Team.add_team(name=t['name'],
                          conference=t['conference'],
                          gm=t['gm'],
                          season=2014)

    with app.open_resource('./testing/data/players.json') as playerdata:
        player_dict = json.load(playerdata)['players']
        for p in player_dict:
            Player.add_player(name=p['name'],
                              positions=p['positions'],
                              team=p['team'])
            Player_Season
    populate_games()
    populate_stats()
    def setUp(self):
        self.app = create_app('testing')
        self.app_context = self.app.app_context()
        self.app_context.push()
        db.create_all()
        #create user roles
        Role.insert_roles()
        #insert matches from the data file
        Team.insert_teams()
        #insert modules
        PredictionModule.insert_modules()
        #insert matches from the data file
        Match.update_all_matches()
        self.u1 = User(email='*****@*****.**', password='******')
        self.u1.confirmed = True
        db.session.add(self.u1)
        db.session.commit()
        matches = Match.query.all()

        # couple of non-played matches
        self.match1 = Match.query.all()[len(matches) - 2]
        self.match2 = Match.query.all()[len(matches) - 1]

        # some played matches
        self.match3 = Match.query.all()[12]
        self.match4 = Match.query.all()[16]

        # draw match
        self.match5 = Match.query.all()[14]

        self.u1.save_match(self.match1)
        self.u1.save_match(self.match2)
        self.u1.save_match(self.match3)
        self.u1.save_match(self.match4)
        self.u1.save_match(self.match5)
        db.session.add(self.u1)
        db.session.commit()
Пример #35
0
    def get_team_key(self, team, campus, semester, team_old=None):
        """
        Get (or create) a team and return its model instance

        :param team: The team data
        :param campus: The campus data
        :return: The team model
        :rtype: app.models.Team
        """
        logging.debug("Getting information about team %s in campus %s and semesters %s", team.code, campus.name,
                      semester.name)
        key = self.generate_team_key(team, campus, semester)
        model_key = ndb.Key(Team, key)
        modified = False
        team_model = None
        if team_old is None:
            logging.debug("Creating team '%s'", team.code)
            team_model = Team(
                key=ndb.Key(Team, key),
                code=team.code,
                vacancies_offered=team.vacancies_offered,
                vacancies_filled=team.vacancies_filled,
                teachers=[],
                schedules=[]
            )
            team_old = json.loads(json.dumps(team_model, cls=JSONEncoder))
            modified = True
        if str(team_old["vacancies_offered"]) != str(team.vacancies_offered):
            logging.warn("The vacancies offered of the team '%s' changed", team.code)
            logging.warn("%s != %s", str(team.vacancies_offered), str(team_old["vacancies_offered"]))
            modified = True
        if str(team_old["vacancies_filled"]) != str(team.vacancies_filled):
            logging.warn("The vacancies filled of the team '%s' changed", team.code)
            logging.warn("%s != %s", str(team.vacancies_filled), str(team_old["vacancies_filled"]))
            modified = True
        if sorted(map(self.generate_teacher_key, team.teachers)) != sorted(map(lambda teacher: str(teacher["id"]), team_old["teachers"])):
            logging.warn("The teachers list of the team '%s' changed", team.code)
            logging.warn("%s != %s", str(sorted(map(self.generate_teacher_key, team.teachers))), str(sorted(map(lambda teacher: str(teacher["id"]), team_old["teachers"]))))
            modified = True
        if sorted(map(self.generate_schedule_key, team.schedules)) != sorted(map(lambda schedule: str(schedule["id"]), team_old["schedules"])):
            logging.warn("The schedules list of the team '%s' changed", team.code)
            logging.warn("%s != %s", str(sorted(map(self.generate_schedule_key, team.schedules))), str(sorted(map(lambda schedule: str(schedule["id"]), team_old["schedules"]))))
            modified = True
        if modified:
            logging.warning("Saving to NDB (team '%s')", team.code)
            if team_model is None:
                team_model = teams_module.get_team(key)
            if team_model is None:
                logging.warning("For some reason the team was not found in cache and its not new...Loading/recreating")
                team_model = yield Team.get_or_insert_async(
                    key,
                    code=team.code,
                    vacancies_offered=team.vacancies_offered,
                    vacancies_filled=team.vacancies_filled,
                    teachers=[],
                    schedules=[],
                    context_options=context_options
                )
            team_model.vacancies_offered = team.vacancies_offered
            team_model.vacancies_filled = team.vacancies_filled
            if sorted(map(self.generate_teacher_key, team.teachers)) != sorted(map(lambda teacher: str(teacher["id"]), team_old["teachers"])):
                team_model.teachers = yield map(self.get_teacher_key, team.teachers)
            if sorted(map(self.generate_schedule_key, team.schedules)) != sorted(map(lambda schedule: str(schedule["id"]), team_old["schedules"])):
                team_model.schedules = yield map(self.get_schedule_key, team.schedules)
            yield team_model.put_async(options=context_options)
            teams_module.get_team(key, overwrite=True, update_with=team_model)
        raise ndb.Return({
            "model": team_model,
            "modified": modified,
            "key": model_key
        })
Пример #36
0
import pandas as pd
from app import db
import sys
from app.models import Team, Ratings

log = logging.getLogger(__name__)

db.create_all()

reload(sys)
sys.setdefaultencoding('utf8')

try:
    teams_data = pd.read_csv("static/test_teams.csv")
    for index, row in teams_data.iterrows():
        team = Team()
        team.team_id   = int(row["team_id"])
        team.team_name = row["team_name"].decode('utf-8')
        team.series_id = int(row["series_id"])
        team.series_name = row["series_name"]
        db.session.add(team)
        db.session.commit()
except Exception as e:
        log.error("Update ViewMenu error: {0}".format(str(e)))
        db.session.rollback()

try:
    teams_data = pd.read_csv("static/test_ratings.csv")
    for index, row in teams_data.iterrows():
        team = Ratings()
        team.team_id   = int(row["team_id"])