def setUp(self): self.winner = ObjectId() self.loser = ObjectId() self.other_player = ObjectId() self.match_id = 1 self.match_id2 = 2 self.excluded1 = False self.excluded2 = True self.match_result = Match(match_id=self.match_id, winner=self.winner, loser=self.loser, excluded=self.excluded1) self.other_match_result = Match(match_id=self.match_id2, winner=self.winner, loser=self.other_player, excluded=self.excluded2) self.match_result_json_dict = { 'match_id': self.match_id, 'winner': self.winner, 'loser': self.loser, 'excluded': self.excluded1 }
class TestMatch(unittest.TestCase): def setUp(self): self.winner = ObjectId() self.loser = ObjectId() self.other_player = ObjectId() self.match_id = 1 self.match_id2 = 2 self.excluded1 = False self.excluded2 = True self.match_result = Match(match_id=self.match_id, winner=self.winner, loser=self.loser, excluded=self.excluded1) self.other_match_result = Match( match_id=self.match_id2, winner=self.winner, loser=self.other_player, excluded=self.excluded2) self.match_result_json_dict = { 'match_id': self.match_id, 'winner': self.winner, 'loser': self.loser, 'excluded': self.excluded1 } def test_contains_players(self): self.assertTrue(self.match_result.contains_players( self.winner, self.loser)) self.assertTrue(self.match_result.contains_players( self.loser, self.winner)) self.assertFalse(self.match_result.contains_players( self.loser, self.loser)) self.assertFalse(self.match_result.contains_players( self.loser, self.other_player)) def test_did_player_win(self): self.assertTrue(self.match_result.did_player_win(self.winner)) self.assertFalse(self.match_result.did_player_win(self.loser)) def test_get_opposing_player_id(self): self.assertEqual(self.match_result.get_opposing_player_id( self.winner), self.loser) self.assertEqual(self.match_result.get_opposing_player_id( self.loser), self.winner) self.assertIsNone( self.match_result.get_opposing_player_id(self.other_player)) def test_dump(self): self.assertEqual(self.match_result.dump( context='db'), self.match_result_json_dict) def test_load(self): self.assertEqual(self.match_result, Match.load( self.match_result_json_dict, context='web')) def test_match_exclusion(self): pass
def _initiate_match(self, creator, joiner): rand = randint(0,1) if rand==0: match = Match(black_player=creator, white_player=joiner) else: match = Match(black_player=joiner, white_player=creator) match.initiate_board() game_list_key = GameList.query(player_key == creator).get().key game_list_key.delete()
def add_match(match_name): """ 增加一场比赛 match_name : 比赛名称,暂时未限定长度,不允许重复 """ session = connectToDatabase() match = Match() match.name = match_name session.add(match) session.commit() match_id = match.id session.close() return match_id
def getAllMatches(self): """ Create classes from list :return: """ res = [] for m in self.matches: res.append(Match(m[0], m[1], m[2], m[3], m[4], m[5])) return res
def _copy_board_to_message(self, matchID): match = Match.get_by_id(matchID) nodes = Match.nodes board_statuses = [] for index, node in enumerate(nodes): board_statuses[index] = int(node) message = BoardStatusResponse(matchID=matchID, board_statuses=board_statuses) return message
def list_matches_by_date(): """Return a list of match list group by date""" matches_by_date = {} for match in Match.fetch_all(): d = date.fromtimestamp(time.mktime(match.date.timetuple())) if not d in matches_by_date: matches_by_date[d] = [] matches_by_date[d].append(match.to_dict()) return json_response(sorted(matches_by_date.values(), key=lambda list: list[0]['date']))
def list_matches(stage_name=None): """Return a list of match according to the stage name""" matches = [] if stage_name is not None: matches_of_this_stage = [match.to_dict() for match in Match.fetch_by_stage(match_stage)] matches_of_this_stage.sort(key=lambda match: match['date']) matches.append(matches_of_this_stage) else: group_stages=['Group '+g for g in ['A','B','C','D','E','F','G','H']] knockoff_stages=['Round of 16','Quarterfinals','Semi-Finals','Third-Place Play-Off','Final'] for match_stage in group_stages: matches_of_this_stage = [match.to_dict() for match in Match.fetch_by_stage(match_stage)] matches_of_this_stage.sort(key=lambda match: match['date']) matches.append(matches_of_this_stage) for match_stage in knockoff_stages: matches_of_this_stage = [match.to_dict() for match in Match.fetch_by_stage(match_stage)] matches_of_this_stage.sort(key=lambda match: match['date']) matches.append(matches_of_this_stage) return json_response(matches)
def popularity(match_id=None): if match_id is None: abort(400) match = Match.fetch_by_id(match_id) final_result = { "team_a":calcPopularity(match.team_a), "team_b":calcPopularity(match.team_b), "match":match.to_dict() } return json_response(final_result)
def choose_run(run_id): """ Making a match when a user chooses a run and sending a text notifying the maker of the run""" asker_id = session['user_id'] asker_name = User.query.get(asker_id).user_name recipient = UserRun.query.get(run_id) recipient_id = recipient.user1 recipient_number = User.query.get(recipient_id).phone recipient_name = User.query.get(recipient_id).user_name new_match = Match(asker_id=session['user_id'], recipient_id=recipient_id, run_id=run_id, asked_at=datetime.datetime.now()) db.session.add(new_match) db.session.commit() match_info = new_match.make_match_dictionary() match_info['recipient_name'] = recipient.user.user_name match_id = int(match_info['match_id']) str_asker_id = str(asker_id) # send a text to person who did the run app to check their email box or respond 'YES' with the match_id. choosing_run(recipient_number, asker_name, match_id) flash("You have just chosen to run with " + recipient_name) return redirect("/users/" + str_asker_id + "/" + asker_name)
def __call__(self, tipp, modus=None): modus = modus or self.LE_MODUS match = Match.get(tipp.match) result = match.result if result: if tipp.result == result: return 4 elif tipp.result[0] - tipp.result[1] == result[0] - result[1]: return 3 elif cmp(tipp.result[0], tipp.result[1]) == cmp(result[0], result[1]): return 2 return 0
def create_match(): if request.method == 'POST': params = request.json print params receiver_id = params['receiver_id'] deliverer_id = params['deliverer_id'] item_type = params['item_type'] item_id = params['item_id'] new_match = Match(receiver_id=receiver_id,deliverer_id=deliverer_id,item_type=item_type,item_id=item_id) g.db.add(new_match) g.db.flush() print "NEW MATCH" print new_match.serialize() g.socketio.emit('match',new_match.serialize(),namespace='/'+new_match.item_type+str(new_match.item_id)) return resource_created(new_match) else: return invalid_method()
def mybet(match_id=None): user = users.get_current_user() if not user: abort(401) else: bets = None if match_id is not None: bets = Bet.query(ndb.AND(Bet.userid==user.user_id(), Bet.bet_match_id==int(match_id))).fetch() else: bets = Bet.query(Bet.userid==user.user_id()).fetch() results = [] for bet in bets: result = bet.to_dict() match = Match.fetch_by_id(bet.bet_match_id) result['match'] = match.to_dict() results.append(result) return json_response(results)
def scrape_results(league_link, league, season): teams = db.get_teams_by_season(season) matches_soup = get_season_matches_as_html(league_link, league.name) matches = [] for match_div in matches_soup: date_time = match_div.find('div', class_='event__time').text date = get_match_year(season, date_time.split(' ')[0]) home_team_name = match_div.find('div', class_='event__participant--home').text away_team_name = match_div.find('div', class_='event__participant--away').text home_team = find_team_by_name(teams, home_team_name) away_team = find_team_by_name(teams, away_team_name) score = match_div.find('div', class_='event__scores').text.replace(' ', '').split('-') home_team_score = score[0] away_team_score = score[1] match = Match(season=season, date=date, home_team=home_team, away_team=away_team, home_team_score=home_team_score, away_team_score=away_team_score) matches.append(match) db.save_matches(matches)
def report_match(match_id=None): user = users.get_current_user() if match_id is None or not user: abort(401) bets = Bet.query(Bet.bet_match_id==int(match_id)).fetch() match = Match.fetch_by_id(match_id) # No report page until 10 minutes prior to the beginning of the match if datetime.utcnow()+timedelta(minutes=10) <= match.date: abort(400) show_known_user = is_known_user(user.email()) bet_results = [] for bet in bets: result = bet.to_dict() result['useremail'] = known_user_name(result['useremail']) result['match'] = match.to_dict() bet_results.append(result) return json_response(bet_results)
def calcPopularity(team_name=None): if team_name is None: abort(400) support = memcache.get('[TeamPop]'+team_name) if support is None: matches = Match.fetch_by_name(team_name) support=0 for match in matches: bets = Bet.query(Bet.bet_match_id==int(match.matchid)).fetch() for bet in bets: if match.team_a == team_name and bet.score_a > bet.score_b: support+=1 elif match.team_b == team_name and bet.score_b > bet.score_a: support+=1 elif match.team_a == team_name and bet.extra_a > bet.extra_b: support+=1 elif match.team_b == team_name and bet.extra_b > bet.extra_a: support+=1 # expire in 5 minutes memcache.set('[TeamPop]'+team_name, support, 300) return support
def setUp(self): self.winner = ObjectId() self.loser = ObjectId() self.other_player = ObjectId() self.match_id = 1 self.match_id2 = 2 self.excluded1 = False self.excluded2 = True self.match_result = Match(match_id=self.match_id, winner=self.winner, loser=self.loser, excluded=self.excluded1) self.other_match_result = Match( match_id=self.match_id2, winner=self.winner, loser=self.other_player, excluded=self.excluded2) self.match_result_json_dict = { 'match_id': self.match_id, 'winner': self.winner, 'loser': self.loser, 'excluded': self.excluded1 }
def add_test_data(): """ 添加测试用的数据 此数据不一定准确,仅做测试用 """ session = connectToDatabase() match = Match() match.name = u"第14届世界杯跳水赛男子单人10米跳台" session.add(match) match = Match() match.name = u"全国跳水冠军赛男子10米跳台" session.add(match) match = Match() match.name = u"雅典奥运会男子10米跳台" session.add(match) player = Player() player.name = u"田亮" player.sex = u"Male" player.age = int(25) player.desc = u"中国重庆人,跳水运动员,演员。前陕西跳水队注册运动员。在2000年悉尼奥运会,获得男子10米跳台跳水冠军;2004年雅典奥运会,和杨景辉一起获得男子双人10米跳台跳水冠军,同时还获得个人季军。" session.add(player) player = Player() player.name = u"胡佳" player.sex = u"Male" player.age = int(24) player.desc = u"湖北武汉人,中国跳水运动员(代表广东汕头)。2004雅典奥运会获得男子10米跳台跳水冠军。" session.add(player) player = Player() player.name = u"孟非" player.sex = u"Male" player.age = int(35) player.desc = u"江苏卫视著名主持人,主持过的节目《南京零距离》、《绝对唱响》、《名师高徒》、《非诚勿扰》" session.add(player) player = Player() player.name = u"秦凯" player.sex = u"Male" player.age = int(25) player.desc = u"中国男子跳水运动员,陕西西安人。" session.add(player) player = Player() player.name = u"郭德纲" player.sex = u"Male" player.age = int(33) player.desc = u"相声" session.add(player) referee = Referee() referee.name = u"乐嘉" referee.sex = u"Male" referee.age = int(36) referee.desc = u"中国性格色彩研究中心创办人,FPA(Four-colors Personality Analysis) 性格色彩创始人,培训师,电视节目主持人。" session.add(referee) referee = Referee() referee.name = u"黄函" referee.sex = u"Female" referee.age = int(47) referee.desc = u"出生于1966年,南京大学。主要著作有《走进震撼的精神世界》、《现代领导方略》、《管理者成功心理学》、《沟通协调能力》等。" session.add(referee) referee = Referee() referee.name = u"八哥" referee.sex = u"Male" referee.age = int(22) referee.desc = u"黑客" session.add(referee) referee = Referee() referee.name = u"球球" referee.sex = u"Male" referee.age = int(23) referee.desc = u"NC" session.add(referee) referee = Referee() referee.name = u"孙翔" referee.sex = u"Male" referee.age = int(22) referee.desc = u"船长" session.add(referee) referee = Referee() referee.name = u"建州" referee.sex = u"Male" referee.age = int(24) referee.desc = u"倒贴型选手" session.add(referee) referee = Referee() referee.name = u"晓敏" referee.sex = u"Male" referee.age = int(22) referee.desc = u"肾不够用了" session.add(referee) referee = Referee() referee.name = u"建模" referee.sex = u"Male" referee.age = int(23) referee.desc = u"投手" session.add(referee) referee = Referee() referee.name = u"YOYO" referee.sex = u"Male" referee.age = int(22) referee.desc = u"校长" session.add(referee) session.commit() session.close()
def bet(match_id, bet_amount=1): """Put down a bet""" user = users.get_current_user() if not user: abort(401) #return redirect(users.create_login_url(url_for('main'))) else: match = Match.fetch_by_id(match_id) # Shutdown bet channel 10 minutes prior to the beginning of the match if datetime.utcnow()+timedelta(minutes=10) > match.date: abort(400) logging.info('betting on %s' % str(match)) # Don't bet on played matches if match.score_a is not None or match.score_b is not None: abort(400) bets = Bet.query(ndb.AND(Bet.userid==user.user_id(), Bet.bet_match_id==int(match_id))).fetch() result = {} score_a = request.args.get('sa',None) score_b = request.args.get('sb',None) extra_a = request.args.get('ea',None) extra_b = request.args.get('eb',None) penalty_a = request.args.get('pa',None) penalty_b = request.args.get('pb',None) #Sanity check #score_a and score_b are mandtary. if score_a is None or score_b is None: logging.warning('missing one of the scores') abort(400) else: #extra_a/extra_b has to appear in pair. if extra_a is not None and extra_b is None: logging.warning('missing extra_b') abort(400) elif extra_a is None and extra_b is not None: logging.warning('missing extra_a') abort(400) #ok, as we have both extra_a/extra_b... elif extra_a is not None and extra_b is not None: # it has to be a tie prediction to involve extra scores if score_a != score_b: logging.warning('not a tie score but extra presents [%d:%d]'%(len(extra_a),len(extra_b))) abort(400) #penalty_a/penalty_b has to appear in pair. elif penalty_a is not None and penalty_b is None: logging.warning('missing penalty_b') abort(400) elif penalty_a is None and penalty_b is not None: logging.warning('missing penalty_a') abort(400) elif penalty_a is not None and penalty_b is not None: # it has to be a tie prediction to involve penalty scores if extra_a != extra_a: logging.warning('not a tie extra but penalty presents') abort(400) #no extra_a/extra_b, no penalty_a/penalty_b allowed else: if penalty_a is not None or penalty_b is not None: logging.warning('no extra but penalty presents') abort(400) if len(bets)==0: bet = Bet(userid=user.user_id(), useremail=user.email(), bet_match_id=int(match_id), bet_amount=int(bet_amount), score_a=int(score_a or 0) if score_a else None, score_b=int(score_b or 0) if score_b else None, extra_a=int(extra_a or 0) if extra_a else None, extra_b=int(extra_b or 0) if extra_b else None, penalty_a=int(penalty_a or 0) if penalty_a else None, penalty_b=int(penalty_b or 0) if penalty_b else None ) logging.info('betting on %s' % str(bet)) bet.put() result = bet.to_dict() else: bet = bets[0] bet.useremail=user.email() bet.bet_amount=int(bet_amount) if score_a: bet.score_a = int(score_a) if score_b: bet.score_b = int(score_b) if extra_a: bet.extra_a = int(extra_a) if extra_b: bet.extra_b = int(extra_b) if penalty_a: bet.penalty_a = int(penalty_a) if penalty_b: bet.penalty_b = int(penalty_b) bet.put() result = bet.to_dict() result['match'] = match.to_dict() return json_response(result)
def test_load(self): self.assertEqual( self.match_result, Match.load(self.match_result_json_dict, context='web'))
class TestMatch(unittest.TestCase): def setUp(self): self.winner = ObjectId() self.loser = ObjectId() self.other_player = ObjectId() self.match_id = 1 self.match_id2 = 2 self.excluded1 = False self.excluded2 = True self.match_result = Match(match_id=self.match_id, winner=self.winner, loser=self.loser, excluded=self.excluded1) self.other_match_result = Match(match_id=self.match_id2, winner=self.winner, loser=self.other_player, excluded=self.excluded2) self.match_result_json_dict = { 'match_id': self.match_id, 'winner': self.winner, 'loser': self.loser, 'excluded': self.excluded1 } def test_contains_players(self): self.assertTrue( self.match_result.contains_players(self.winner, self.loser)) self.assertTrue( self.match_result.contains_players(self.loser, self.winner)) self.assertFalse( self.match_result.contains_players(self.loser, self.loser)) self.assertFalse( self.match_result.contains_players(self.loser, self.other_player)) def test_did_player_win(self): self.assertTrue(self.match_result.did_player_win(self.winner)) self.assertFalse(self.match_result.did_player_win(self.loser)) def test_get_opposing_player_id(self): self.assertEqual(self.match_result.get_opposing_player_id(self.winner), self.loser) self.assertEqual(self.match_result.get_opposing_player_id(self.loser), self.winner) self.assertIsNone( self.match_result.get_opposing_player_id(self.other_player)) def test_dump(self): self.assertEqual(self.match_result.dump(context='db'), self.match_result_json_dict) def test_load(self): self.assertEqual( self.match_result, Match.load(self.match_result_json_dict, context='web')) def test_match_exclusion(self): pass
def setUp(self): self.player_1_id = ObjectId() self.player_2_id = ObjectId() self.player_3_id = ObjectId() self.player_4_id = ObjectId() self.player_5_id = ObjectId() self.player_6_id = ObjectId() self.player_1 = Player(name='gar', id=self.player_1_id) self.player_2 = Player(name='sfat', id=self.player_2_id) self.player_3 = Player(name='shroomed', id=self.player_3_id) self.player_4 = Player(name='ppu', id=self.player_4_id) self.player_5 = Player(name='ss', id=self.player_5_id) self.player_6 = Player(name='hmw', id=self.player_6_id) self.match_1 = Match(winner=self.player_1_id, loser=self.player_2_id) self.match_2 = Match(winner=self.player_3_id, loser=self.player_4_id) self.match_1 = AliasMatch(winner=self.player_1.name, loser=self.player_2.name) self.match_2 = AliasMatch(winner=self.player_3.name, loser=self.player_4.name) self.alias_to_id_map = [ AliasMapping(player_alias=self.player_1.name, player_id=self.player_1_id), AliasMapping(player_alias=self.player_2.name, player_id=self.player_2_id), AliasMapping(player_alias=self.player_3.name, player_id=self.player_3_id), AliasMapping(player_alias=self.player_4.name, player_id=self.player_4_id) ] self.id = ObjectId() self.type = 'tio' self.raw_id = ObjectId() self.date = datetime.now() self.name = 'tournament' self.players = [ self.player_1.name, self.player_2.name, self.player_3.name, self.player_4.name ] self.matches = [self.match_1, self.match_2] self.regions = ['norcal', 'texas'] self.url = 'http://challonge.com/test' self.excluded = False self.pending_tournament_json_dict = { '_id': self.id, 'type': self.type, 'raw_id': self.raw_id, 'date': self.date, 'name': self.name, 'players': self.players, 'matches': [m.dump(context='db') for m in self.matches], 'regions': self.regions, 'alias_to_id_map': [am.dump(context='db') for am in self.alias_to_id_map], 'excluded': False, 'url': self.url } self.pending_tournament = PendingTournament( id=self.id, name=self.name, type=self.type, date=self.date, regions=self.regions, url=self.url, raw_id=self.raw_id, players=self.players, matches=self.matches, excluded=self.excluded, alias_to_id_map=self.alias_to_id_map)
def bestbet(): user = users.get_current_user() if not user: abort(401) else: show_known_user = is_known_user(user.email()) final_results = memcache.get('[BestBet]'+str(show_known_user)) if final_results is None: if show_known_user: matches = Match.fetch_all() finished_matches = [] for match in matches: if match.score_a is not None and match.score_b is not None: finished_matches.append(match) finished_matches = sorted(finished_matches, cmp=lambda x, y:cmp(x.date,y.date)) results = {} #key:useremail/known_name, value:rightAboutScore/rightAboutWin slipped_award = 0.0 for match in finished_matches: bets = Bet.fetch_by_matchid(match.matchid) #collect slipped award award_pool = {'total_amount':len(known_users)*3.0+slipped_award,'bingo_count':0,'bingo_user':[]} slipped_award = 0.0 for bet in bets: #only process known users if not is_known_user(bet.useremail) or bet.useremail=='*****@*****.**' or bet.useremail=='*****@*****.**': logging.info('%s is not known user, skip it.' % str(bet.useremail)) continue #replace with known name bet.useremail = known_user_name(bet.useremail) #initialize results for this user if bet.useremail not in results: results[bet.useremail] = {'rightAboutScore':0,'rightAboutWin':0,'points':0} #Bingo! if match.score_a == bet.score_a and match.score_b == bet.score_b and match.extra_a == bet.extra_a and match.extra_b == bet.extra_b: results[bet.useremail]['rightAboutScore']+=1 award_pool['bingo_count']+=1 award_pool['bingo_user'].append(bet.useremail) if cmp(match.score_a, match.score_b) == cmp(bet.score_a, bet.score_b): if match.extra_a is not None and match.extra_b is not None: if bet.extra_a is not None and bet.extra_b is not None: if cmp(match.extra_a, match.extra_b) == cmp(bet.extra_a, bet.extra_b): results[bet.useremail]['rightAboutWin']+=1 else: results[bet.useremail]['rightAboutWin']+=1 #no one bingo, the pool goes to next match if award_pool['bingo_count'] == 0: slipped_award = award_pool['total_amount'] logging.info('Award %d of match between %s and %s slipped to next match' % (slipped_award, match.team_a, match.team_b)) else: award = award_pool['total_amount']/award_pool['bingo_count'] logging.info('Award %d of match between %s and %s got distributed to following users, %d for each: %s' % (award_pool['total_amount'], match.team_a, match.team_b, award, ','.join(award_pool['bingo_user']))) for awarded_user in award_pool['bingo_user']: results[awarded_user]['points']+=award #sort by points/rightAboutScore/rightAboutWin for output final_results = sorted(results.iteritems(), reverse=True, cmp=lambda x, y: cmp(x[1]['points'], y[1]['points']) or cmp(x[1]['rightAboutScore'], y[1]['rightAboutScore']) or cmp(x[1]['rightAboutWin'],y[1]['rightAboutWin'])) final_results = {"slipped_award":slipped_award, "results":final_results} else: #not known user: bets = Bet.fetch_all() results = {} for bet in bets: #only process bets of finished matches match = Match.fetch_by_id(bet.bet_match_id) if match.score_a is None or match.score_b is None: continue #statistic if bet.useremail not in results: results[bet.useremail] = {'rightAboutScore':0,'rightAboutWin':0} result = results[bet.useremail] #Bingo! if match.score_a == bet.score_a and match.score_b == bet.score_b and match.extra_a == bet.extra_a and match.extra_b == bet.extra_b: results[bet.useremail]['rightAboutScore']+=1 if cmp(match.score_a, match.score_b) == cmp(bet.score_a, bet.score_b): if match.extra_a is not None and match.extra_b is not None: if bet.extra_a is not None and bet.extra_b is not None: if cmp(match.extra_a, match.extra_b) == cmp(bet.extra_a, bet.extra_b): results[bet.useremail]['rightAboutWin']+=1 else: results[bet.useremail]['rightAboutWin']+=1 final_results = sorted(results.iteritems(), reverse=True, cmp=lambda x, y: cmp(x[1]['rightAboutScore'], y[1]['rightAboutScore']) or cmp(x[1]['rightAboutWin'],y[1]['rightAboutWin'])) final_results = {"slipped_award":0, "results":final_results} # expire in 5 minutes memcache.set('[BestBet]'+str(show_known_user), final_results, 300) return json_response(final_results)
def admin(): """Admin page""" if users.is_current_user_admin(): logout_url = users.create_logout_url('/admin') method = request.args.get('m', '') logging.info('Method name:[%s]' % method) if method == 'dropdb': match_keys = Match.query().fetch(keys_only=True) ndb.delete_multi(match_keys) return render_template('admin.html', msg='Matches all deleted!', logout_url=logout_url) if method == 'dropbet': if not isLocal(): abort(401) bet_keys = Bet.query().fetch(keys_only=True) ndb.delete_multi(bet_keys) return render_template('admin.html', msg='Bet all deleted!', logout_url=logout_url) elif method == 'initdb': with open('worldcup2014-group-stage.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: match = Match(matchid=int(row[0]), date=datetime.strptime( str(row[1]), "%m/%d/%Y %H:%M"), stage=row[5], team_a=row[2], team_b=row[3], score_a=None, score_b=None, extra_a=None, extra_b=None, penalty_a=None, penalty_b=None) match.put() return render_template('admin.html', msg='Matches imported!', logout_url=logout_url) elif method == 'initdb2': with open('worldcup2014-knockoff-stage.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: match = Match(matchid=int(row[0]), date=datetime.strptime( str(row[1]), "%m/%d/%Y %H:%M"), stage=row[5], team_a='winner of ' + row[2], team_b='winner of ' + row[3], score_a=None, score_b=None, extra_a=None, extra_b=None, penalty_a=None, penalty_b=None) match.put() return render_template('admin.html', msg='Matches imported!', logout_url=logout_url) elif method == 'randombetwithknownuser': for useremail in known_users.keys(): #drop existing first existing_bets = Bet.query(Bet.useremail == useremail).fetch( keys_only=True) ndb.delete_multi(existing_bets) #new data digits = 21 uid = str(int(random.random() * 10**digits)).rjust(digits, '0') matches = Match.query().fetch() for match in matches: bet = Bet(userid=uid, useremail=useremail, bet_match_id=int(match.matchid), bet_amount=1, score_a=random.randint(0, 3), score_b=random.randint(0, 3), extra_a=None, extra_b=None, penalty_a=None, penalty_b=None) bet.put() return render_template( 'admin.html', msg='simulated bets for known user has been generated!', logout_url=logout_url) elif method == 'randombet': digits = 21 uid = str(int(random.random() * 10**digits)).rjust(digits, '0') digits = 3 email = '*****@*****.**' % int(random.random() * 10**digits) matches = Match.query().fetch() for match in matches: bet = Bet(userid=uid, useremail=email, bet_match_id=int(match.matchid), bet_amount=1, score_a=random.randint(0, 3), score_b=random.randint(0, 3), extra_a=None, extra_b=None, penalty_a=None, penalty_b=None) bet.put() return render_template( 'admin.html', msg='simulated bets for %s has been generated!' % uid, logout_url=logout_url) elif method == 'insertmatch': match_id = int(request.args.get('id', 0)) team_a = request.args.get('a', None) or None team_b = request.args.get('b', None) or None match_stage = request.args.get('s', None) or None match_date = request.args.get('d', None) or None score_a = request.args.get('sa', None) or None or None score_b = request.args.get('sb', None) or None extra_a = request.args.get('ea', None) or None extra_b = request.args.get('eb', None) or None penalty_a = request.args.get('pa', None) or None penalty_b = request.args.get('pb', None) or None matches = Match.query(Match.matchid == match_id).fetch() if len(matches) == 0: match = Match(matchid=match_id, date=datetime.strptime(match_date, "%d %B %Y %H:%M"), stage=match_stage, team_a=team_a, team_b=team_b, score_a=None, score_b=None, extra_a=None, extra_b=None, penalty_a=None, penalty_b=None) logging.info('insert attempt:%s' % str(match)) match.put() return render_template( 'admin.html', msg='Match between %s and %s has been inserted!' % (match.team_a, match.team_b), logout_url=logout_url) else: match = matches[0] if match_date: match.date = datetime.strptime(match_date, "%d %B %Y %H:%M") if match_stage: match.stage = match_stage if team_a: match.team_a = team_a if team_b: match.team_b = team_b if score_a: match.score_a = int(score_a) if score_b: match.score_b = int(score_b) if extra_a: match.extra_a = int(extra_a) if extra_b: match.extra_b = int(extra_b) if penalty_a: match.penalty_a = int(penalty_a) if penalty_b: match.penalty_b = int(penalty_b) logging.info('update attempt:%s' % str(match)) match.put() return render_template( 'admin.html', msg='Match between %s and %s has been updated!' % (match.team_a, match.team_b)) elif method == 'sendmail': match_id = int(request.args.get('id', 0)) subject = request.args.get('s', None) or None body = request.args.get('b', None) or None html = request.args.get('h', None) or None logging.info('sendmail attempt:%s' % str(match_id)) if match_id > 0: bets = Bet.query(Bet.bet_match_id == match_id).fetch() match = Match.query(Match.matchid == match_id).fetch()[0] addresses = [] [addresses.append(str(bet.useremail)) for bet in bets] target_address = ';'.join(addresses) #subject = "Match between %s and %s just started!" %(match.team_a, match.team_b) #body = "http://localhost:8080/#/my" #html = "<a href=\"http://localhost:8080/#/my\">My guess</a>" send_mail(target_address, subject, body, html) return render_template( 'admin.html', msg='Mail to %s with <%s> has succeeded!' % (target_address, subject)) return render_template('admin.html', msg='You have to specify match id!', logout_url=logout_url) return render_template('admin.html', logout_url=logout_url) else: return render_template('logout.html', logout_url=users.create_logout_url( request.path), login_url=users.create_login_url(request.path))
def setUp(self): self.player_1_id = ObjectId() self.player_2_id = ObjectId() self.player_3_id = ObjectId() self.player_4_id = ObjectId() self.player_5_id = ObjectId() self.player_6_id = ObjectId() self.player_1 = Player(name='gar', id=self.player_1_id) self.player_2 = Player(name='sfat', id=self.player_2_id) self.player_3 = Player(name='shroomed', id=self.player_3_id) self.player_4 = Player(name='ppu', id=self.player_4_id) self.player_5 = Player(name='ss', id=self.player_5_id) self.player_6 = Player(name='hmw', id=self.player_6_id) self.match_1 = Match(winner=self.player_1_id, loser=self.player_2_id, match_id=1) self.match_2 = Match(winner=self.player_3_id, loser=self.player_4_id, match_id=2) self.alias_to_id_map = [ AliasMapping(player_alias=self.player_2.name, player_id=self.player_2_id), AliasMapping(player_alias=self.player_1.name, player_id=self.player_1_id), AliasMapping(player_alias=self.player_3.name, player_id=self.player_3_id), AliasMapping(player_alias=self.player_4.name, player_id=self.player_4_id) ] self.id = ObjectId() self.type = 'tio' self.raw_id = ObjectId() self.date = datetime.now() self.name = 'tournament' self.url = "challonge.com/tournament" self.player_ids = [ self.player_1_id, self.player_2_id, self.player_3_id, self.player_4_id ] self.players = [ self.player_1, self.player_2, self.player_3, self.player_4 ] self.matches = [self.match_1, self.match_2] self.regions = ['norcal', 'texas'] self.tournament_json_dict = { '_id': self.id, 'type': self.type, 'raw_id': self.raw_id, 'date': self.date, 'name': self.name, 'url': self.url, 'players': self.player_ids, 'orig_ids': self.player_ids, 'matches': [m.dump(context='db') for m in self.matches], 'regions': self.regions } self.tournament = Tournament(id=self.id, name=self.name, type=self.type, date=self.date, regions=self.regions, url=self.url, raw_id=self.raw_id, players=self.player_ids, orig_ids=self.player_ids, matches=self.matches)
def admin(): """Admin page""" if users.is_current_user_admin(): logout_url=users.create_logout_url('/admin') method = request.args.get('m','') logging.info('Method name:[%s]' % method) if method == 'dropdb': match_keys = Match.query().fetch(keys_only=True) ndb.delete_multi(match_keys) return render_template('admin.html', msg='Matches all deleted!', logout_url=logout_url) if method == 'dropbet': if not isLocal(): abort(401) bet_keys = Bet.query().fetch(keys_only=True) ndb.delete_multi(bet_keys) return render_template('admin.html', msg='Bet all deleted!', logout_url=logout_url) elif method == 'initdb': with open('worldcup2014-group-stage.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: match = Match( matchid=int(row[0]), date=datetime.strptime(str(row[1]), "%m/%d/%Y %H:%M"), stage=row[5], team_a=row[2], team_b=row[3], score_a=None, score_b=None, extra_a=None, extra_b=None, penalty_a=None, penalty_b=None ) match.put() return render_template('admin.html', msg='Matches imported!', logout_url=logout_url) elif method == 'initdb2': with open('worldcup2014-knockoff-stage.csv', 'rb') as csvfile: spamreader = csv.reader(csvfile) for row in spamreader: match = Match( matchid=int(row[0]), date=datetime.strptime(str(row[1]), "%m/%d/%Y %H:%M"), stage=row[5], team_a='winner of '+row[2], team_b='winner of '+row[3], score_a=None, score_b=None, extra_a=None, extra_b=None, penalty_a=None, penalty_b=None ) match.put() return render_template('admin.html', msg='Matches imported!', logout_url=logout_url) elif method == 'randombetwithknownuser': for useremail in known_users.keys(): #drop existing first existing_bets = Bet.query(Bet.useremail==useremail).fetch(keys_only=True) ndb.delete_multi(existing_bets) #new data digits = 21 uid = str(int(random.random()*10**digits)).rjust(digits,'0') matches = Match.query().fetch() for match in matches: bet = Bet( userid=uid, useremail=useremail, bet_match_id=int(match.matchid), bet_amount=1, score_a=random.randint(0,3), score_b=random.randint(0,3), extra_a=None, extra_b=None, penalty_a=None, penalty_b=None ) bet.put() return render_template('admin.html', msg='simulated bets for known user has been generated!', logout_url=logout_url) elif method == 'randombet': digits = 21 uid = str(int(random.random()*10**digits)).rjust(digits,'0') digits = 3 email = '*****@*****.**'%int(random.random()*10**digits) matches = Match.query().fetch() for match in matches: bet = Bet( userid=uid, useremail=email, bet_match_id=int(match.matchid), bet_amount=1, score_a=random.randint(0,3), score_b=random.randint(0,3), extra_a=None, extra_b=None, penalty_a=None, penalty_b=None ) bet.put() return render_template('admin.html', msg='simulated bets for %s has been generated!'%uid, logout_url=logout_url) elif method == 'insertmatch': match_id = int(request.args.get('id',0)) team_a = request.args.get('a',None) or None team_b = request.args.get('b',None) or None match_stage = request.args.get('s',None) or None match_date = request.args.get('d',None) or None score_a = request.args.get('sa',None) or None or None score_b = request.args.get('sb',None) or None extra_a = request.args.get('ea',None) or None extra_b = request.args.get('eb',None) or None penalty_a = request.args.get('pa',None) or None penalty_b = request.args.get('pb',None) or None matches = Match.query(Match.matchid==match_id).fetch() if len(matches)==0: match = Match( matchid=match_id, date=datetime.strptime(match_date, "%d %B %Y %H:%M"), stage=match_stage, team_a=team_a, team_b=team_b, score_a=None, score_b=None, extra_a=None, extra_b=None, penalty_a=None, penalty_b=None ) logging.info('insert attempt:%s' % str(match)) match.put() return render_template('admin.html', msg='Match between %s and %s has been inserted!' % (match.team_a, match.team_b), logout_url=logout_url) else: match = matches[0] if match_date: match.date = datetime.strptime(match_date, "%d %B %Y %H:%M") if match_stage: match.stage = match_stage if team_a: match.team_a = team_a if team_b: match.team_b = team_b if score_a: match.score_a = int(score_a) if score_b: match.score_b = int(score_b) if extra_a: match.extra_a = int(extra_a) if extra_b: match.extra_b = int(extra_b) if penalty_a: match.penalty_a = int(penalty_a) if penalty_b: match.penalty_b = int(penalty_b) logging.info('update attempt:%s' % str(match)) match.put() return render_template('admin.html', msg='Match between %s and %s has been updated!' % (match.team_a, match.team_b)) elif method == 'sendmail': match_id = int(request.args.get('id',0)) subject = request.args.get('s',None) or None body = request.args.get('b',None) or None html = request.args.get('h',None) or None logging.info('sendmail attempt:%s' % str(match_id)) if match_id > 0: bets = Bet.query(Bet.bet_match_id==match_id).fetch() match = Match.query(Match.matchid==match_id).fetch()[0] addresses = [] [addresses.append(str(bet.useremail)) for bet in bets] target_address = ';'.join(addresses) #subject = "Match between %s and %s just started!" %(match.team_a, match.team_b) #body = "http://localhost:8080/#/my" #html = "<a href=\"http://localhost:8080/#/my\">My guess</a>" send_mail(target_address, subject, body, html) return render_template('admin.html', msg='Mail to %s with <%s> has succeeded!' % (target_address, subject)) return render_template('admin.html',msg='You have to specify match id!', logout_url=logout_url) return render_template('admin.html', logout_url=logout_url) else: return render_template('logout.html', logout_url=users.create_logout_url(request.path), login_url=users.create_login_url(request.path))
def create_matches(self): return [ Match(group="A", home_team="Бразилия", guest_team="Хорватия", start=datetime.combine(date(2014, 06, 12), time(23, 0))), Match(group="A", home_team="Мексика", guest_team="Камерун", start=datetime.combine(date(2014, 06, 13), time(19, 0))), Match(group="B", home_team="Испания", guest_team="Нидерланды", start=datetime.combine(date(2014, 06, 13), time(22, 0))), Match(group="B", home_team="Чили", guest_team="Австралия", start=datetime.combine(date(2014, 06, 14), time(1, 0))), Match(group="C", home_team="Колумбия", guest_team="Греция", start=datetime.combine(date(2014, 06, 14), time(19, 0))), Match(group="D", home_team="Уругвай", guest_team="Коста-Рика", start=datetime.combine(date(2014, 06, 14), time(22, 0))), Match(group="D", home_team="Англия", guest_team="Италия", start=datetime.combine(date(2014, 06, 15), time(1, 0))), Match(group="C", home_team="Кот д'Ивуар", guest_team="Япония", start=datetime.combine(date(2014, 06, 15), time(4, 0))), Match(group="E", home_team="Швейцария", guest_team="Эквадор", start=datetime.combine(date(2014, 06, 15), time(19, 0))), Match(group="E", home_team="Франция", guest_team="Гондурас", start=datetime.combine(date(2014, 06, 15), time(22, 0))), Match(group="F", home_team="Аргентина", guest_team="Босния", start=datetime.combine(date(2014, 06, 16), time(1, 0))), Match(group="G", home_team="Германия", guest_team="Португалия", start=datetime.combine(date(2014, 06, 16), time(19, 0))), Match(group="F", home_team="Иран", guest_team="Нигерия", start=datetime.combine(date(2014, 06, 16), time(22, 0))), Match(group="G", home_team="Гана", guest_team="США", start=datetime.combine(date(2014, 06, 17), time(1, 0))), Match(group="H", home_team="Бельгия", guest_team="Алжир", start=datetime.combine(date(2014, 06, 17), time(19, 0))), Match(group="A", home_team="Бразилия", guest_team="Мексика", start=datetime.combine(date(2014, 06, 17), time(22, 0))), Match(group="H", home_team="Россия", guest_team="Южная Корея", start=datetime.combine(date(2014, 06, 18), time(1, 0))), Match(group="B", home_team="Австралия", guest_team="Нидерланды", start=datetime.combine(date(2014, 06, 18), time(19, 0))), Match(group="B", home_team="Испания", guest_team="Чили", start=datetime.combine(date(2014, 06, 18), time(22, 0))), Match(group="A", home_team="Камерун", guest_team="Хорватия", start=datetime.combine(date(2014, 06, 19), time(1, 0))), Match(group="C", home_team="Колумбия", guest_team="Кот д'Ивуар", start=datetime.combine(date(2014, 06, 19), time(19, 0))), Match(group="D", home_team="Уругвай", guest_team="Англия", start=datetime.combine(date(2014, 06, 19), time(22, 0))), Match(group="C", home_team="Япония", guest_team="Греция", start=datetime.combine(date(2014, 06, 20), time(1, 0))), Match(group="D", home_team="Италия", guest_team="Коста-Рика", start=datetime.combine(date(2014, 06, 20), time(19, 0))), Match(group="E", home_team="Швейцария", guest_team="Франция", start=datetime.combine(date(2014, 06, 20), time(22, 0))), Match(group="E", home_team="Гондурас", guest_team="Эквадор", start=datetime.combine(date(2014, 06, 21), time(1, 0))), Match(group="F", home_team="Аргентина", guest_team="Иран", start=datetime.combine(date(2014, 06, 21), time(19, 0))), Match(group="G", home_team="Германия", guest_team="Гана", start=datetime.combine(date(2014, 06, 21), time(22, 0))), Match(group="F", home_team="Нигерия", guest_team="Босния", start=datetime.combine(date(2014, 06, 22), time(1, 0))), Match(group="H", home_team="Бельгия", guest_team="Россия", start=datetime.combine(date(2014, 06, 22), time(19, 0))), Match(group="H", home_team="Южная Корея", guest_team="Алжир", start=datetime.combine(date(2014, 06, 22), time(22, 0))), Match(group="G", home_team="США", guest_team="Португалия", start=datetime.combine(date(2014, 06, 23), time(1, 0))), Match(group="B", home_team="Австралия", guest_team="Испания", start=datetime.combine(date(2014, 06, 23), time(19, 0))), Match(group="B", home_team="Нидерланды", guest_team="Чили", start=datetime.combine(date(2014, 06, 23), time(19, 0))), Match(group="A", home_team="Камерун", guest_team="Бразилия", start=datetime.combine(date(2014, 06, 23), time(23, 0))), Match(group="A", home_team="Хорватия", guest_team="Мексика", start=datetime.combine(date(2014, 06, 23), time(23, 0))), Match(group="D", home_team="Коста-Рика", guest_team="Англия", start=datetime.combine(date(2014, 06, 24), time(19, 0))), Match(group="D", home_team="Италия", guest_team="Уругвай", start=datetime.combine(date(2014, 06, 24), time(19, 0))), Match(group="C", home_team="Греция", guest_team="Кот д'Ивуар", start=datetime.combine(date(2014, 06, 24), time(23, 0))), Match(group="C", home_team="Япония", guest_team="Колумбия", start=datetime.combine(date(2014, 06, 24), time(23, 0))), Match(group="F", home_team="Нигерия", guest_team="Аргентина", start=datetime.combine(date(2014, 06, 25), time(19, 0))), Match(group="F", home_team="Босния", guest_team="Иран", start=datetime.combine(date(2014, 06, 25), time(19, 0))), Match(group="E", home_team="Гондурас", guest_team="Швейцария", start=datetime.combine(date(2014, 06, 25), time(23, 0))), Match(group="E", home_team="Эквадор", guest_team="Франция", start=datetime.combine(date(2014, 06, 25), time(23, 0))), Match(group="G", home_team="США", guest_team="Германия", start=datetime.combine(date(2014, 06, 26), time(19, 0))), Match(group="G", home_team="Португалия", guest_team="Гана", start=datetime.combine(date(2014, 06, 26), time(19, 0))), Match(group="H", home_team="Алжир", guest_team="Россия", start=datetime.combine(date(2014, 06, 26), time(23, 0))), Match(group="H", home_team="Южная Корея", guest_team="Бельгия", start=datetime.combine(date(2014, 06, 26), time(23, 0))) ]
def test_load(self): self.assertEqual(self.match_result, Match.load( self.match_result_json_dict, context='web'))
def fillOutMatch(SESSION, match, name, id): user = SESSION.query(User).filter(User.id == id).filter( User.name == name).one() d = datetime.strptime(match['started_at'], "%Y-%m-%dT%H:%M:%S%z") _m = SESSION.query(Match).filter(Match.user_id==user.id).\ filter(Match.user_name==user.name).\ filter(Match.date==d).\ filter(Match.id==match['match_id']).all() #Don't add duplicate data if len(_m) > 0: #my_print("duplicate data!") return True participant = match['participant'] stats = participant['stats'] combat = stats['combat'] m = Match() m.pubg_id = participant['_id'] # 2018-01-24T03:10:17+0000 m.date = d m.id = match['match_id'] m.mode = match['mode'] m.queue_size = match['queue_size'] m.rank = stats['rank'] m.rating_delta = stats['rating_delta'] m.boosts = combat['boosts'] m.damage = combat['damage']['damage_dealt'] m.knocks = combat['dbno']['knock_downs'] m.revives = combat['dbno']['revives'] m.death_type = combat['death_type'] m.ride_distance = combat['distance_traveled']['ride_distance'] m.walk_distance = combat['distance_traveled']['walk_distance'] m.distance_traveled = m.ride_distance + m.walk_distance m.heals = combat['heals'] m.assists = combat['kda']['assists'] m.headshot_kills = combat['kda']['headshot_kills'] m.kill_steaks = combat['kda']['kill_steaks'] m.kills = combat['kda']['kills'] m.longest_kill = combat['kda']['longest_kill'] m.road_kills = combat['kda']['road_kills'] m.team_kills = combat['kda']['team_kills'] m.kda = m.kills + m.assists m.kill_place = combat['kill_place'] m.most_damage = combat['most_damage'] m.time_survived = combat['time_survived'] m.vehicle_destroys = combat['vehicle_destroys'] m.weapon_acquired = combat['weapon_acquired'] m.win_place = combat['win_place'] m.user_id = user.id m.user_name = user.name m.user.append(user) user.matches.append(m) SESSION.add(m) return False
def setUp(self): self.mongo_client.drop_database(DATABASE_NAME) self.player_1_id = ObjectId() self.player_2_id = ObjectId() self.player_3_id = ObjectId() self.player_4_id = ObjectId() self.player_5_id = ObjectId() self.player_1 = Player(name='gaR', aliases=['gar', 'garr'], ratings={ 'norcal': Rating(), 'texas': Rating() }, regions=['norcal', 'texas'], id=self.player_1_id) self.player_2 = Player(name='sfat', aliases=['sfat', 'miom | sfat'], ratings={'norcal': Rating()}, regions=['norcal'], id=self.player_2_id) self.player_3 = Player(name='mango', aliases=['mango', 'gar'], ratings={'norcal': Rating(mu=2, sigma=3)}, regions=['socal'], id=self.player_3_id) self.player_4 = Player(name='shroomed', aliases=['shroomed'], ratings={'norcal': Rating()}, regions=['norcal'], id=self.player_4_id) self.player_5 = Player(name='pewpewu', aliases=['pewpewu'], ratings={'norcal': Rating()}, regions=['norcal', 'socal'], id=self.player_5_id) self.merge_player_1 = Player(name='CLGsFaT', aliases=['clg | sfat'], ratings={'norcal': Rating()}, regions=['norcal'], id=ObjectId()) # only includes players 1-3 self.players = [self.player_1, self.player_2, self.player_3] self.tournament_id_1 = ObjectId() self.tournament_type_1 = 'tio' self.tournament_raw_id_1 = ObjectId() self.tournament_date_1 = datetime(2013, 10, 16) self.tournament_name_1 = 'tournament 1' self.tournament_players_1 = [ self.player_1_id, self.player_2_id, self.player_3_id, self.player_4_id ] self.tournament_matches_1 = [ Match(winner=self.player_1_id, loser=self.player_2_id), Match(winner=self.player_3_id, loser=self.player_4_id) ] self.tournament_regions_1 = ['norcal'] # tournament 2 is earlier than tournament 1, but inserted after self.tournament_id_2 = ObjectId() self.tournament_type_2 = 'challonge' self.tournament_raw_id_2 = ObjectId() self.tournament_date_2 = datetime(2013, 10, 10) self.tournament_name_2 = 'tournament 2' self.tournament_players_2 = [ self.player_5_id, self.player_2_id, self.player_3_id, self.player_4_id ] self.tournament_matches_2 = [ Match(winner=self.player_5_id, loser=self.player_2_id), Match(winner=self.player_3_id, loser=self.player_4_id) ] self.tournament_regions_2 = ['norcal', 'texas'] self.tournament_1 = Tournament(id=self.tournament_id_1, name=self.tournament_name_1, type=self.tournament_type_1, date=self.tournament_date_1, regions=self.tournament_regions_1, raw_id=self.tournament_raw_id_1, players=self.tournament_players_1, matches=self.tournament_matches_1) self.tournament_2 = Tournament(id=self.tournament_id_2, name=self.tournament_name_2, type=self.tournament_type_2, date=self.tournament_date_2, regions=self.tournament_regions_2, raw_id=self.tournament_raw_id_2, players=self.tournament_players_2, matches=self.tournament_matches_2) self.tournament_ids = [self.tournament_id_1, self.tournament_id_2] self.tournaments = [self.tournament_1, self.tournament_2] self.pending_tournament_id_1 = ObjectId() self.pending_tournament_type_1 = 'tio' self.pending_tournament_raw_id_1 = ObjectId() self.pending_tournament_date_1 = datetime(2013, 10, 11) self.pending_tournament_name_1 = 'pending tournament 1' self.pending_tournament_players_1 = [ self.player_1.name, self.player_2.name, self.player_3.name, self.player_4.name ] self.pending_tournament_matches_1 = [ AliasMatch(winner=self.player_1.name, loser=self.player_2.name), AliasMatch(winner=self.player_3.name, loser=self.player_4.name) ] self.pending_tournament_regions_1 = ['norcal'] self.pending_tournament_1 = PendingTournament( id=self.pending_tournament_id_1, name=self.pending_tournament_name_1, type=self.pending_tournament_type_1, date=self.pending_tournament_date_1, regions=self.pending_tournament_regions_1, raw_id=self.pending_tournament_raw_id_1, players=self.pending_tournament_players_1, matches=self.pending_tournament_matches_1) self.pending_tournaments = [self.pending_tournament_1] self.ranking_entry_1 = RankingEntry(rank=1, player=self.player_1_id, rating=20) self.ranking_entry_2 = RankingEntry(rank=2, player=self.player_2_id, rating=19) self.ranking_entry_3 = RankingEntry(rank=3, player=self.player_3_id, rating=17.5) self.ranking_entry_4 = RankingEntry(rank=3, player=self.player_4_id, rating=16.5) self.ranking_time_1 = datetime(2013, 4, 20) self.ranking_time_2 = datetime(2013, 4, 21) self.ranking_1 = Ranking(id=ObjectId(), region='norcal', time=self.ranking_time_1, tournaments=self.tournament_ids, ranking=[ self.ranking_entry_1, self.ranking_entry_2, self.ranking_entry_3 ]) self.ranking_2 = Ranking(id=ObjectId(), region='norcal', time=self.ranking_time_2, tournaments=self.tournament_ids, ranking=[ self.ranking_entry_1, self.ranking_entry_2, self.ranking_entry_4 ]) self.ranking_3 = Ranking( id=ObjectId(), region='norcal', time=self.ranking_time_2, tournaments=self.tournament_ids, ranking=[self.ranking_entry_1, self.ranking_entry_2]) self.rankings = [self.ranking_1, self.ranking_2, self.ranking_3] self.user_id_1 = 'abc123' self.user_admin_regions_1 = ['norcal', 'texas'] self.user_1 = User(id=self.user_id_1, admin_regions=self.user_admin_regions_1, username='******', salt='nacl', hashed_password='******') self.user_id_2 = 'asdfasdf' self.user_full_name_2 = 'Full Name' self.user_admin_regions_2 = [] self.user_2 = User(id=self.user_id_2, admin_regions=self.user_admin_regions_2, username=self.user_full_name_2, salt='nacl', hashed_password='******') self.users = [self.user_1, self.user_2] self.region_1 = Region(id='norcal', display_name='Norcal') self.region_2 = Region(id='texas', display_name='Texas') self.regions = [self.region_1, self.region_2] for region in self.regions: Dao.insert_region(region, self.mongo_client, database_name=DATABASE_NAME) self.norcal_dao = Dao('norcal', self.mongo_client, database_name=DATABASE_NAME) for player in self.players: self.norcal_dao.insert_player(player) for tournament in self.tournaments: self.norcal_dao.insert_tournament(tournament) for pending_tournament in self.pending_tournaments: self.norcal_dao.insert_pending_tournament(pending_tournament) for ranking in self.rankings: self.norcal_dao.insert_ranking(ranking) for user in self.users: self.norcal_dao.insert_user(user)
def add_match(): """ We create a match object, 2 teamps and get the players """ form = Form_add_match(request.form) if request.method == "POST": # Creation object Match match = Match() # Get the players team1_players = request.form.getlist("team1_select") team2_players = request.form.getlist("team2_select") team1_players = form.team1_select.data team2_players = form.team2_select.data print(team1_players) print(team2_players) # Get the results of the match # result1 = request.form.get("result1") # result2 = request.form.get("result2") result1 = form.result1.data result2 = form.result2.data #Creation of the teams team1 = Team(result=result1) team2 = Team(result=result2) # # Cration association object : play for each player in the match # team1play1 = Play(result=result1, match_id=match.id) # team2play1 = Play(result=result2, match_id=match.id) # Set the player and add to the match team1player1 = Player.query.filter_by(id=int(team1_players[0])).first() team2player1 = Player.query.filter_by(id=int(team2_players[0])).first() team1.players.append(team1player1) team2.players.append(team2player1) # Set the second players if they played if len(team1_players) > 1: team1player2 = Player.query.filter_by( id=int(team1_players[1])).first() team1.players.append(team1player2) if len(team2_players) > 1: team2player2 = Player.query.filter_by( id=int(team2_players[1])).first() team2.players.append(team2player2) # Add the both teams to the matchs match.teams.append(team1) match.teams.append(team2) # Add in the database and commit db.session.add(match) db.session.commit() return redirect(url_for(".show_matchs")) else: players = Player.query.all() list_players = [] for player in players: list_players.append(player.get_tuple_player()) form.team1_select.choices = list_players form.team2_select.choices = list_players return render_template("add_match.html", players=players, form=form)