def put(self, request): """ Adds a team. """ try: post_fields = read_json(request.body) except ValueError: return HttpResponse(_("JSON, please!"), status=400) try: assert type(post_fields['name']) is str assert type(post_fields['players']) is list for item in post_fields['players']: assert type(item) is str except (AssertionError, KeyError): return HttpResponse(_("Hack attempt detected."), status=400) team = Team() team.race = self.token.race team.name = post_fields['name'] team.save() for player_name in post_fields['players']: player = Player() player.team = team player.name = player_name player.save() response = { 'id': team.pk } return HttpResponse(make_json(response), status=200)
def check_team_existence_or_create(name, tourny, team_name="enter_names", dryrun=True): try: teams = Team.objects.filter(team_code = name) # check to make sure that the team is actually entered # this is to solve when a team is in rounds but wasnt on the entries page if len(teams) > 1: team = None for the_team in teams: if team_name != "enter_names" and the_team.team_name == team_name: team = the_team break if not team: return teams[0] if not team: team = Team(team_code = name, team_name= team_name) if not dryrun: team.save() team.tournaments.add(tourny) else: team = teams[0] if tourny not in Tournament.objects.filter(entries__id=team.id): team.tournaments.add(tourny) return team except: print "making team: " + name team = Team(team_code = name, team_name= team_name) if not dryrun: team.save() team.tournaments.add(tourny) return team
def initial_comp_setup(): round_setup() for round in range(1, ROUNDS + 1): logger.info("Fetching round %s/%s...", round, ROUNDS) start = datetime.now() r = requests.get( "http://api.stats.foxsports.com.au/3.0/api/sports/league/series/1/seasons/116/rounds/" + str(round) + "/fixturesandresultswithbyes.json?userkey=A00239D3-45F6-4A0A-810C-54A347F144C2" ) if round == 1: # Setup teams if they don't already exist team_ids = list(Team.objects.values_list('fox_id', flat=True)) for game in json.loads(r.text): team = {} team['name'] = game["team_A"]["name"] + ' ' + game["team_A"][ "short_name"] team['fox_id'] = game["team_A"]["id"] if team['fox_id'] not in team_ids: team_ids.append(team['fox_id']) logger.info("Adding team %s to teams", team['name']) new_team = Team(name=team['name'], fox_id=team['fox_id']) new_team.save() team = {} team['name'] = game["team_B"]["name"] + ' ' + game["team_B"][ "short_name"] team['fox_id'] = game["team_B"]["id"] if team['fox_id'] not in team_ids: team_ids.append(team['fox_id']) logger.info("Adding team %s to teams", team['name']) new_team = Team(name=team['name'], fox_id=team['fox_id']) new_team.save() for game in json.loads(r.text): fixture_id = game["fixture_id"] round_object = Round.objects.get(round=round) game_time = parse_datetime(game["match_start_date"]) home_team = Team.objects.get(fox_id=game["team_A"]["id"]) away_team = Team.objects.get(fox_id=game["team_B"]["id"]) stadium = game["venue"]["name"] new_game = Game(fixture_id=fixture_id, start_time=game_time, round=round_object, home_team=home_team, away_team=away_team, stadium=stadium) new_game.save() end = datetime.now() elapsed_time = end - start if elapsed_time.total_seconds() < 5: time.sleep(5 - elapsed_time.total_seconds())
def port_csv_to_db(): csv_path = "/home/ubuntu/test-bigdata/new_bd_resp.csv" df = pd.read_csv(csv_path) for index, row in df.iterrows(): try: team_obj = Team(team_name=row["Enter team name"], member_1=row["Team member 1 email"], member_2=row["Team member 2 email"], member_3=row["Team member 3 email"], member_4=row["Team member 4 email"]) team_obj.save() except Exception as e: print(e) print("Invalid row")
def register_boat(data): boat = Boat(name=data['name'], boat_class_id=data['boat_class'], boat_number=data['boat_number'], tech_inspection=data['tech_inspection']) try: boat.save() team = Team(boat_id=boat.id, member_id=data['member']) team.save() return HttpResponse(renderers.JSONRenderer().render({'status': '1'})) except db.DataError as e: return HttpResponse(renderers.JSONRenderer().render({ 'status': '0', 'error': e }))
def create_team(data): print(data) token = Token.objects.get(token=data['auth_token']) for member in data['member']: team = Team(boat_id=Team.objects.get(member_id=token.user_id).boat_id, member_id=member) try: team.save() Member.objects.filter(id=member).update(take_part_flag=False) except db.DataError as e: return HttpResponse(renderers.JSONRenderer().render({ 'status': '0', 'error': e })) return HttpResponse(renderers.JSONRenderer().render("lol"))
def initial_comp_setup(): round_setup() for round in range(1, ROUNDS+1): logger.info("Fetching round %s/%s...", round, ROUNDS) start = datetime.now() r = requests.get("http://api.stats.foxsports.com.au/3.0/api/sports/league/series/1/seasons/114/rounds/"+str(round)+"/fixturesandresultswithbyes.json?userkey=A00239D3-45F6-4A0A-810C-54A347F144C2") if round==1: teams = [] for game in json.loads(r.text): team = {} team['name']=game["team_A"]["name"]+' '+game["team_A"]["short_name"] team['fox_id']=game["team_A"]["id"] if team not in teams: teams.append(team) logger.info("Adding team %s to teams", team['name']) new_team=Team(name=team['name'], fox_id=team['fox_id']) new_team.save() team = {} team['name']=game["team_B"]["name"]+' '+game["team_B"]["short_name"] team['fox_id']=game["team_B"]["id"] if team not in teams: teams.append(team) logger.info("Adding team %s to teams", team['name']) new_team=Team(name=team['name'], fox_id=team['fox_id']) new_team.save() for game in json.loads(r.text): fixture_id = game["fixture_id"] round_object = Round.objects.get(round=round) game_time = parse_datetime(game["match_start_date"]) home_team = Team.objects.get(fox_id=game["team_A"]["id"]) away_team = Team.objects.get(fox_id=game["team_B"]["id"]) stadium = game["venue"]["name"] new_game = Game(fixture_id=fixture_id, start_time = game_time, round=round_object, home_team=home_team, away_team=away_team, stadium=stadium) new_game.save() end = datetime.now() elapsed_time = end-start if elapsed_time.total_seconds()<5: time.sleep(5 - elapsed_time.total_seconds())
def enter_team_list(url, tournament, dryrun=True): team_list = get_team_list(url) tourny = Tournament.objects.get(tournament_name = tournament) for (code, names) in team_list: code = tp.team_code(code) try: team = Team.objects.get(team_code = code) if team.team_name != names: team = Team(team_code = code, team_name = name) print "got team %s" % code team.tournaments.add(tourny) except: team = Team(team_code = code, team_name = names) if not dryrun: team.save() team.tournaments.add(tourny) print "made team %s" % code
def create_users(): user_1 = User.objects.create_user("testuser1", "*****@*****.**", "test123") user_2 = User.objects.create_user("testuser2", "*****@*****.**", "test123") user_3 = User.objects.create_user("testuser3", "*****@*****.**", "test123") user_4 = User.objects.create_user("testuser4", "*****@*****.**", "test123") user_5 = User.objects.create_user("testuser5", "*****@*****.**", "test123") user_6 = User.objects.create_user("testuser6", "*****@*****.**", "test123") team_1 = Team(name="Team 1", description="Team 1") team_1.save() team_2 = Team(name="Team 2", description="Team 2") team_2.save() team_3 = Team(name="Team 3", description="Team 3") team_3.save() emp_1 = Employee(user=user_1, team=team_1, name="Test 1") emp_1.save() emp_2 = Employee(user=user_2, team=team_1, name="Test 2") emp_2.save() emp_3 = Employee(user=user_3, team=team_2, name="Test 3") emp_3.save() emp_4 = Employee(user=user_4, team=team_2, name="Test 4") emp_4.save() emp_5 = Employee(user=user_5, team=team_3, name="Test 5") emp_5.save() emp_6 = Employee(user=user_6, team=team_3, name="Test 6") emp_6.save()
def get_teams_by_summoner_id(summoner_id, region): """ Get team data, given a summoner ID and region, and stores it in the DB. Each summoner can have 0 or more teams. This checks for matching teams in the DB and updates them if they are present, otherwise it creates a new team. Matches are made by comparing region and full_id. Team queries to the Riot API return the following data, per team: -timestamps for roster invites -timestamps for roster joins -summoner IDs for team roster -summoner ID for team owner -match summary for each game played -summary for overall performance in 5v5 and 3v3 -team basic data (e.g. tag, name, etc) -timestamps for most recent game, team modified, team created """ # Riot API returns HTTP 404 if summoner is not on any teams. try: teams_dto = riot_api.get_teams_for_summoner(summoner_id, region) got_teams = True except LoLException as e: got_teams = False if e == error_404: print('Summoner ID', summoner_id, 'is not on any teams (error_404).') else: got_teams = False print('ERROR getting teams:', e) if got_teams: # teams_dto is a list that will contain an entry for each team the summoner is on. for team in teams_dto: # Can we match this data to a Team in the DB? try: matching_team = Team.objects.filter(region=region).get(full_id=team['fullId']) # We found a match, so set the working Team to that. print('Found matching Team {} {}'.format(matching_team.region, matching_team.name)) matched = True new_team = matching_team except ObjectDoesNotExist: # No match found, so create a new Team. matched = False print('No matching team found. Creating a new Team...') new_team = Team() # We get all the Team data from Riot API call, # so we can delete everything and just create new models below. if matched: new_team.roster.delete() new_team.delete() # Set everything in the Team model that isn't a related field. new_team.create_date = team['createDate'] new_team.full_id = team['fullId'] # If team hasn't played a game (this season?) if 'lastGameDate' in team: new_team.last_game_date = team['lastGameDate'] new_team.last_joined_ranked_team_queue_date = team['lastJoinedRankedTeamQueueDate'] new_team.modify_date = team['modifyDate'] new_team.name = team['name'] new_team.last_join_date = team['lastJoinDate'] new_team.second_last_join_date = team['secondLastJoinDate'] new_team.third_last_join_date = team['thirdLastJoinDate'] new_team.status = team['status'] new_team.tag = team['tag'] new_team.region = region # This leaves: roster, teamStatDetails, matchHistory. roster_dto = team['roster'] team_stat_details_dto = team['teamStatDetails'] # If team hasn't played a game (extends past this season, so no games played ever!) if 'matchHistory' in team: match_history_dto = team['matchHistory'] # Setup and save the Roster model. new_roster = Roster(owner_id=roster_dto['ownerId']) new_roster.save() # We can set the roster relation on the Team model now, and save it. new_team.roster = new_roster new_team.save() # Setup and save the TeamMemberInfo models for this Roster. for member in roster_dto['memberList']: new_member = TeamMemberInfo(invite_date=member['inviteDate'], join_date=member['joinDate'], player_id=member['playerId'], status=member['status'], roster=new_roster) new_member.save() # Setup and save the TeamStatDetail models for the Team. for stats in team_stat_details_dto: new_stats = TeamStatDetail(team_stat_type=stats['teamStatType'], average_games_played=stats['averageGamesPlayed'], wins=stats['wins'], losses=stats['losses'], team=new_team) new_stats.save() # Setup and save the MatchHistorySummary models for the Team, if it has a history. if match_history_dto: for match in match_history_dto: new_match = MatchHistorySummary(assists=match['assists'], date=match['date'], deaths=match['deaths'], game_id=match['gameId'], game_mode=match['gameMode'], invalid=match['invalid'], kills=match['kills'], map_id=match['mapId'], opposing_team_kills=match['opposingTeamKills'], opposing_team_name=match['opposingTeamName'], win=match['win'], team=new_team) new_match.save()
def get_teams_by_summoner_id(summoner_id, region): """ Get team data, given a summoner ID and region, and stores it in the DB. Each summoner can have 0 or more teams. This checks for matching teams in the DB and updates them if they are present, otherwise it creates a new team. Matches are made by comparing region and full_id. Team queries to the Riot API return the following data, per team: -timestamps for roster invites -timestamps for roster joins -summoner IDs for team roster -summoner ID for team owner -match summary for each game played -summary for overall performance in 5v5 and 3v3 -team basic data (e.g. tag, name, etc) -timestamps for most recent game, team modified, team created """ # Riot API returns HTTP 404 if summoner is not on any teams. try: teams_dto = riot_api.get_teams_for_summoner(summoner_id, region) got_teams = True except LoLException as e: got_teams = False if e == error_404: print('Summoner ID', summoner_id, 'is not on any teams (error_404).') else: got_teams = False print('ERROR getting teams:', e) if got_teams: # teams_dto is a list that will contain an entry for each team the summoner is on. for team in teams_dto: # Can we match this data to a Team in the DB? try: matching_team = Team.objects.filter(region=region).get( full_id=team['fullId']) # We found a match, so set the working Team to that. print('Found matching Team {} {}'.format( matching_team.region, matching_team.name)) matched = True new_team = matching_team except ObjectDoesNotExist: # No match found, so create a new Team. matched = False print('No matching team found. Creating a new Team...') new_team = Team() # We get all the Team data from Riot API call, # so we can delete everything and just create new models below. if matched: new_team.roster.delete() new_team.delete() # Set everything in the Team model that isn't a related field. new_team.create_date = team['createDate'] new_team.full_id = team['fullId'] # If team hasn't played a game (this season?) if 'lastGameDate' in team: new_team.last_game_date = team['lastGameDate'] new_team.last_joined_ranked_team_queue_date = team[ 'lastJoinedRankedTeamQueueDate'] new_team.modify_date = team['modifyDate'] new_team.name = team['name'] new_team.last_join_date = team['lastJoinDate'] new_team.second_last_join_date = team['secondLastJoinDate'] new_team.third_last_join_date = team['thirdLastJoinDate'] new_team.status = team['status'] new_team.tag = team['tag'] new_team.region = region # This leaves: roster, teamStatDetails, matchHistory. roster_dto = team['roster'] team_stat_details_dto = team['teamStatDetails'] # If team hasn't played a game (extends past this season, so no games played ever!) if 'matchHistory' in team: match_history_dto = team['matchHistory'] # Setup and save the Roster model. new_roster = Roster(owner_id=roster_dto['ownerId']) new_roster.save() # We can set the roster relation on the Team model now, and save it. new_team.roster = new_roster new_team.save() # Setup and save the TeamMemberInfo models for this Roster. for member in roster_dto['memberList']: new_member = TeamMemberInfo(invite_date=member['inviteDate'], join_date=member['joinDate'], player_id=member['playerId'], status=member['status'], roster=new_roster) new_member.save() # Setup and save the TeamStatDetail models for the Team. for stats in team_stat_details_dto: new_stats = TeamStatDetail( team_stat_type=stats['teamStatType'], average_games_played=stats['averageGamesPlayed'], wins=stats['wins'], losses=stats['losses'], team=new_team) new_stats.save() # Setup and save the MatchHistorySummary models for the Team, if it has a history. if match_history_dto: for match in match_history_dto: new_match = MatchHistorySummary( assists=match['assists'], date=match['date'], deaths=match['deaths'], game_id=match['gameId'], game_mode=match['gameMode'], invalid=match['invalid'], kills=match['kills'], map_id=match['mapId'], opposing_team_kills=match['opposingTeamKills'], opposing_team_name=match['opposingTeamName'], win=match['win'], team=new_team) new_match.save()