def createPlayerShotokan(request, tournament_id): template = loader.get_template('shotokanCreatePlayer.html') if request.method == 'POST': form = ShotokanPlayerCreateForm(request.POST) if form.is_valid(): player = Player( name=form.cleaned_data.get('name'), surname=form.cleaned_data.get('surname'), team_id=Team.objects.get(name=form.cleaned_data.get('teams')), acceptedbycoachteam=True, acceptedbyplayer=True) player.save() player_tournament = PlayerTournament( player_id=player, tournament_id=Tournament.objects.get(pk=tournament_id), acceptedbymanager=True, acceptedbycoach=True) player_tournament.save() return redirect('/shotokanPlayers/%s/' % tournament_id) else: form = ShotokanPlayerCreateForm() context = RequestContext(request, { 'form': form, }) return HttpResponse(template.render(context))
def edit(request): if not request.user.is_authenticated(): return HttpResponseRedirect('/tf2recruiter/openid/') try: player = Player.objects.get(user=request.user) except Player.DoesNotExist: player = Player() if request.method == 'POST': form = PlayerForm(request.POST, instance=player) if form.is_valid(): player.user=request.user player.alias = form.cleaned_data['alias'] player.seasons = form.cleaned_data['seasons'] days = '' for day in form.cleaned_data['days']: days = days + day player.days = days player.eseaid = form.cleaned_data['eseaid'] es = '' for e in form.cleaned_data['esea']: es = es + e player.esea = es player.save() player.classes = form.cleaned_data['classes'] player.save() return HttpResponseRedirect('/tf2recruiter/') else: form = PlayerForm(instance=player) return render_to_response('form.htm', { 'form': form, 'action':'/tf2recruiter/edit', 'user_':request.user}, context_instance=RequestContext(request))
def login_player(request): t = str(time.time()) player_name = request.POST["player_name"] request.session["player_name"] = player_name request.session["mode"] = request.POST["mode"] request.session["room_id"] = None if request.POST["mode"] == "solo": player = Player(name=player_name, created_at=t) player.save() request.session["player_id"] = list( Player.objects.all().filter(created_at=t).values("id"))[0]["id"] elif request.POST["mode"] == "multi": room_name = request.POST["room_name"] room_id = list( Room.objects.all().filter(name=room_name).values())[0]["id"] room_num = list( Room.objects.all().filter(name=room_name).values())[0]["num"] player_num = len( list(Player.objects.all().filter(room_id=room_id).values())) if player_num >= room_num: return HttpResponse("false") request.session["room_id"] = room_id player = Player(name=player_name, created_at=t) player.save() request.session["player_id"] = list( Player.objects.all().filter(created_at=t).values("id"))[0]["id"] obj = Player.objects.get(id=request.session["player_id"]) obj.room_id = room_id obj.save() # return HttpResponseRedirect("/mode/solo") return HttpResponse("true")
def get_player_info(): """Acquires basic info of all current NBA players and stores in DB.""" player_ids = [p.player_id for p in PlayerID.objects.all()] params_ = {'LeagueID' : LEAGUE_ID, 'SeasonType' : SEASON_TYPE} Player.objects.all().delete() count = 1 for play_id in player_ids: try: params_['PlayerID'] = play_id request = get(URL, params=params_).json() info_list = request['resultSets'][0]['rowSet'][0] info = Player() info.name = info_list[3] info.number = info_list[13] info.image = URL_IMAGE % play_id info.year_enter_league = info_list[22] info.position = info_list[14] info.height = info_list[10] info.weight = info_list[11] info.current_team = '%s %s' % (info_list[20], info_list[17]) info.player_id = play_id info.save() print count, info.name count += 1 except Exception, e: LOGGER.log(ERROR, 'Player Info Error') LOGGER.log(ERROR, 'ID: %d' % play_id) LOGGER.log(ERROR, 'Error: %s' % e)
def populate_players_model(): # Loop through the top level dictionary for team, value in premier_league_players_dictionary.items(): # Loop through the players in each team for player_name, val in value['squad_players'].items(): # Create a new player instance for each player player_entry = Player(club=Club.objects.get(club=team), player=player_name, club_name=team, position=val['position'], nationality=val['nationality']) player_entry.save()
def register(request): error = {'username': '', 'email': '', 'password2': ''} if request.method == 'POST': form = RegisterForm(request.POST) error = form.errors if form.is_valid(): confirm = User.objects.create_user(username = form.cleaned_data['username'], email = form.cleaned_data['email'], password = form.cleaned_data['password2']) confirm.save u = User.objects.get(username = form.cleaned_data['username']) foreign = Player(username = u, email = form.cleaned_data['email'], totalgame = 0, totalwin = 0, times_today = 0, percent = 0, money = 100, user_id = u.id, last_reg = date.today()) foreign.save() return HttpResponseRedirect('/login/') else: form = RegisterForm() return render_to_response('register.html', {'error_user': error.get('username'), 'error_email': error.get('email'), 'error_password': error.get('password2')})
def register(response): if response.method == "POST": form = RegistrationForm(response.POST) if form.is_valid(): #*Creating new RegistrationForm object which we will store in our database n = form.cleaned_data['username'] p = Player(name=n) p.save() response.user.player.add(p) #*Logging in by default #!Cannot forget to save the form itself because authentication won't work otherwise form.save() return redirect("/login") else: form = RegistrationForm() if response.user.is_authenticated: u = Player.objects.get(id=response.user.id) return render(response, "register/register.html", {"form": form, "user": u, "logged_in": True}) else: return render(response, "register/register.html", {"form": form, "logged_in": False})
def populate_player(): print('Cargando jugadores...') Player.objects.all().delete() main_directory = 'info_champ' directory = main_directory + '/' + 'players' lista = [] ix = open_dir(directory) with ix.searcher() as searcher: doc = searcher.documents() for row in doc: p = Player(idPlayer=row['idPlayer'], name=row['name'], urlPerfil=row['urlPerfil'], ranking=row['ranking'], winrate=row['winrate']) listChampion = [] for id in row['idsChampion'].split(','): champion = Champion.objects.get(idChampion=id) listChampion.append(champion) p.save() p.idsChampion.set(listChampion) lista.append(p) print('Jugadores insertados: ' + str(Player.objects.count())) print('---------------------------------------------------------')
class Db(object): """ Helper class to create test data in db. """ def __init__(self): self.db_name = connection.settings_dict['NAME'] print(self.db_name) self.team = None self.cache = None self.player = None self.season = None self.ladder = None self.ranking = None self.ranking_data = None self.default_ranking_data__data = {} self.clear_defaults() def clear_defaults(self): self.default_ranking_data__data = {} @staticmethod def filter(klass, *args, **kwargs): return klass.objects.filter(*args, **kwargs) @staticmethod def count(klass, *args, **kwargs): return klass.objects.filter(*args, **kwargs).count() @staticmethod def get(klass, *args, **kwargs): return klass.objects.get(*args, **kwargs) @staticmethod def objects(klass): return klass.objects @staticmethod def all(klass): return klass.objects.all() @staticmethod def execute(sql): cursor = connection.cursor() cursor.execute(sql) return cursor def delete_all(self, keep=None, delete=None): for d in (delete or [ RankingData, RankingStats, Cache, Ranking, Team, Player, Ladder, Season ]): if d not in (keep or []): if d == Ranking: cursor = connection.cursor() cursor.execute("update cache set ranking_id = NULL") if d == Ladder: cursor = connection.cursor() cursor.execute("update cache set ladder_id = NULL") self.all(d).delete() def create_season(self, **kwargs): kwargs = merge_args( { 'id': 16, 'start_date': '2013-11-11', 'end_date': '2014-01-03', 'name': '2013 Season 6', 'year': 2013, 'number': 6, 'version': Version.HOTS }, **kwargs) try: self.get(Season, id=kwargs['id']) raise AssertionError("Season with id %d already exists." % kwargs['id']) except Season.DoesNotExist: pass self.season = Season(**kwargs) self.season.save() return self.season def create_cache(self, type=Cache.LADDER, members=None, **kwargs): data = kwargs.pop('data', None) if data is None and members is not None: data = gen_ladder_data(members) kwargs = merge_args( { 'bid': randint(1, 1e6), 'url': 'http://bnet/' + uniqueid(10), 'type': type, 'region': Region.EU, 'created': utcnow(), 'updated': utcnow(), 'status': 200, 'retry_count': 0 }, **kwargs) kwargs['data'] = json.dumps(data) self.cache = Cache(**kwargs) self.cache.save() return self.cache def create_ladder(self, **kwargs): kwargs = merge_args( { 'bid': 1, 'region': Region.EU, 'strangeness': Ladder.GOOD, 'league': League.GOLD, 'tier': 0, 'version': Version.HOTS, 'mode': Mode.TEAM_1V1, 'season': self.season, 'first_join': utcnow(), 'last_join': utcnow(), 'created': utcnow(), 'updated': utcnow(), 'max_points': 20 }, **kwargs) self.ladder = Ladder(**kwargs) self.ladder.save() return self.ladder def create_player(self, **kwargs): kwargs = merge_args( { 'bid': randint(0, 1e9), 'region': Region.EU, 'realm': 1, 'mode': Mode.TEAM_1V1, 'season': self.season, 'race': Race.ZERG, 'name': uniqueid(12), 'clan': uniqueid(32), 'tag': uniqueid(6) }, **kwargs) self.player = Player(**kwargs) self.player.save() return self.player def create_team(self, **kwargs): kwargs = merge_args( dict(region=Region.EU, mode=Mode.TEAM_1V1, season=self.season, version=Version.HOTS, league=League.GOLD, member0=self.player, member1=None, member2=None, member3=None, race0=Race.ZERG, race1=Race.UNKNOWN, race2=Race.UNKNOWN, race3=Race.UNKNOWN), **kwargs) self.team = Team(**kwargs) self.team.save() return self.team def create_teams(self, count=1, **kwargs): teams = [] for i in range(count): self.create_player(name="%s-%d" % (uniqueid(8), i)) teams.append(self.create_team(**kwargs)) return teams def get_teams_by_member0_bids(self, *bids, mode=Mode.TEAM_1V1): tids = [] for bid in bids: p = self.get(Player, bid=bid) tids.append(self.get(Team, member0=p, mode=mode).id) return tids def create_ranking(self, **kwargs): kwargs = merge_args( dict(created=utcnow(), data_time=utcnow(), min_data_time=utcnow(), max_data_time=utcnow(), status=Ranking.COMPLETE_WITH_DATA, season=self.season), **kwargs) self.ranking = Ranking.objects.create(**kwargs) return self.ranking def _default_team_rank(self, team_rank): """ Update a team_rank dict with defaults. """ for k, v in self.default_ranking_data__data.items(): team_rank.setdefault(k, v) team_rank.setdefault("team_id", self.team.id) team_rank.setdefault("data_time", to_unix(self.ranking.data_time)) team_rank.setdefault("version", Version.HOTS) team_rank.setdefault("region", Region.EU) team_rank.setdefault("mode", Mode.TEAM_1V1) team_rank.setdefault("league", League.GOLD) team_rank.setdefault("tier", 0) team_rank.setdefault("ladder_id", self.ladder.id) team_rank.setdefault("join_time", to_unix(self.ranking.data_time)) team_rank.setdefault("source_id", self.cache.id) team_rank.setdefault("mmr", 1000) team_rank.setdefault("points", 100.0) team_rank.setdefault("wins", 10) team_rank.setdefault("losses", 10) team_rank.setdefault("race0", Race.ZERG) team_rank.setdefault("race1", Race.UNKNOWN) team_rank.setdefault("race2", Race.UNKNOWN) team_rank.setdefault("race3", Race.UNKNOWN) team_rank.setdefault("ladder_rank", 1) team_rank.setdefault("ladder_count", 1) team_rank.setdefault("league_rank", 1) team_rank.setdefault("league_count", 1) team_rank.setdefault("region_rank", 1) team_rank.setdefault("region_count", 1) team_rank.setdefault("world_rank", 1) team_rank.setdefault("world_count", 1) def create_ranking_data(self, raw=True, **kwargs): kwargs = merge_args(dict(ranking=self.ranking, updated=utcnow()), kwargs) data = kwargs.pop('data', []) ranking = kwargs['ranking'] for team_rank in data: self._default_team_rank(team_rank) ranking.sources.add(self.get(Cache, pk=team_rank['source_id'])) self.ranking_data = RankingData.objects.create(**kwargs) sc2.save_ranking_data_raw(self.db_name, ranking.id, 0, data, True) if not raw: cpp = sc2.RankingData(self.db_name, Enums.INFO) cpp.load(ranking.id) cpp.save_data(ranking.id, ranking.season_id, to_unix(utcnow())) cpp.release() return self.ranking_data def update_ranking_stats(self, ranking_id=None): """ Will build ranking stats based of the ranking by calling c++. """ if ranking_id is None: ranking_id = self.ranking.id cpp = sc2.RankingData(self.db_name, Enums.INFO) cpp.load(ranking_id) cpp.save_stats(ranking_id, to_unix(utcnow())) cpp.release()
def index(request): channel_id = '423486275' if request.method == 'POST': username = request.POST['mc-username'] print(username) # username validation for i in username: if i.upper() not in string.ascii_uppercase + '0123456789_': # raise ValidationError raise Exception('Юзернейм неверен.') twitch_id = request.POST.get('id') obj = Player.objects.get(twitch_id=twitch_id, mc_username=None) obj.mc_username = username obj.save() return render(request, 'thanks.html', context={'username': username}) # TODO: username at thanks.html else: if request.GET.get('code'): # getting user information resp = requests.post('https://id.twitch.tv/oauth2/token', data={ 'client_id': 'geqwz9a4dhcg3wcmv8qsu07p5bb9cx', 'client_secret': '37cs0vpf6k3l3s71d3e8ios99ql6wi', 'code': request.GET.get('code'), 'grant_type': 'authorization_code', 'redirect_uri': 'http://' + DOMAIN_NAME, }).json() access_token = resp.get('access_token') if not access_token: return render(request, '500.html', context={ 'title': 'Ошибка, попробуйте переавторизоваться.' }) headers = { 'Accept': 'application/vnd.twitchtv.v5+json', 'Client-ID': 'geqwz9a4dhcg3wcmv8qsu07p5bb9cx', 'Authorization': 'OAuth %s' % access_token } user_id = requests.get('https://api.twitch.tv/helix/users', headers={ 'Accept': 'application/vnd.twitchtv.v5+json', 'Client-ID': 'geqwz9a4dhcg3wcmv8qsu07p5bb9cx', 'Authorization': 'Bearer %s' % access_token }).json().get('data')[0].get('id') # checking if he is subbed resp2 = requests.get( 'https://api.twitch.tv/kraken/users/%s/subscriptions/%s' % (user_id, channel_id), headers=headers).json() if resp2.get('status') == 404: return render(request, 'not_subbed.html', context={'debug': str([resp, resp2])}) obj = Player(twitch_id=user_id, mc_username=None) try: obj.save() except IntegrityError: if not Player.objects.filter(twitch_id=user_id, mc_username=None).exists(): return render( request, '500.html', context={'title': 'Ты уже добавлен в вайтлист.'}) return render(request, 'add.html', context={'twitch_id': user_id}) return render(request, 'index.html', context={'test_id': channel_id})
def incoming_text(request): league_from_number = request.GET.get('league') league = None if league_from_number: league = League.objects.get(shorthand_name=league_from_number) number = request.GET.get('From') msg = request.GET.get('Body').lower().replace('\n', '') sections = msg.split(" ") try: player = Player.objects.get(phone_number=number) if not player.username: player.username = msg player.save() return HttpResponse(createSmsResponse(COMMANDS_MSG)) except: player = Player(phone_number=number) player.save() if league: return HttpResponse(createSmsResponse("Welcome to {0} on Undisputed. Enter your initials.".format(league.name))) else: return HttpResponse(createSmsResponse("Welcome to Undisputed. Enter your initials.")) # join undisputed username firstname lastname # TODO- all other valid characters, regex check on each section if re.match("^me$",msg): return handle_me(number) # options elif re.match("^options$",msg): return HttpResponse(createSmsResponse(COMMANDS_MSG)) elif re.match("^lost to [a-zA-z0-9_]+$", msg) and league_from_number: sections = [sections[0], sections[2], "in", league_from_number] return handle_win(number, sections, True) elif re.match("^beat [a-zA-z0-9_]+$", msg) and league_from_number: sections = sections + ["in", league_from_number] return handle_win(number, sections) # beat opponent1 (and opponent2 with partner )in competition_name elif re.match("^beat [a-zA-z0-9_]+ (and [a-zA-z0-9_]+ with [a-zA-z0-9_]+ )?in [a-zA-z0-9_]+$", msg): return handle_win(number, sections) # competition_name rankings elif re.match("^rankings$", msg) and league_from_number: sections = [league_from_number] + sections return handle_rank(number,sections) # competition_name rankings elif re.match("^[a-zA-z0-9_]+ rankings$", msg): return handle_rank(number,sections) # my competition_name stats elif re.match("^my stats$", msg) and league_from_number: sections = ['my', league_from_number, 'stats'] return handle_stats(number,sections) # my competition_name stats elif re.match("^my [a-zA-z0-9_]+( [a-zA-z0-9_]+)? stats$", msg): sections = msg.split(" ") return handle_stats(number,sections) # create solo|partner|partnered league name password # TODO: league name multiple words? elif re.match("^create (solo|partnered|partner) league [a-zA-Z0-9_]+ [a-zA-Z0-9_]+$", msg): return handle_create_league(number, sections) # join league_name password (with partner): elif re.match("^join [a-zA-Z0-9_]+ [a-zA-Z0-9_]+( with [a-zA-Z ]+)?$",msg): return handle_join_league(number, sections) else: return HttpResponse(createSmsResponse("Not recognized. Text 'options' to view your options."))