Riot 전적 분석 프로젝트 - 2

jkky98·2024년 3월 18일
1

Project

목록 보기
17/21

MATCH-V5의 지표들에 모두 익숙해졌다. 이제 본격적으로 전적분석 데이터 분석 어플리케이션 작업을 위해 API로 데이터를 불러들여야한다. 워낙 복잡하고 거대하게 짜여져 있다보니 많은 작업이 필요하다.

일단 매치정보를 모으기 전에, 설계를 먼저하였다. 간단하게 기존 전적분석 웹 서비스처럼 전적갱신 버튼의 방식을 채용해볼까 한다.

화면단 디자인은 맨 나중 작업이므로 UPDATE버튼이 눌렸을 때 기본 프로필의 변화감지 및 전적을 갱신해야한다.

    Update() {
      axiosInstance
        .post("http://localhost:8000/api/update/", {
          userId: this.userId,
        })
        .then((res) => {
          console.log(res.data);
          this.name = res.data.name;
          this.level = res.data.summonerLevel;
          this.icon = res.data.profileIconId;
          this.iconUrl = "../assets/profileicon/" + this.icon + ".png";
        })
        .catch((err) => {
          console.log(err);
        });
    },

간단하게 Update 메소드를 작성해서 백엔드로 post request를 날려준다. 이제 백엔드쪽을 작업해본다.

일단 Riot 회원에 대한 데이터베이스를 만들기 위해 모델을 하나 짠다.

class UserRiot(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE, default=0)
    riot_id = models.CharField(max_length=1000, default="")
    riot_puuid = models.CharField(max_length=1000, default="")
    revision_date = models.CharField(max_length=1000, default="")
    summonerLevel = models.IntegerField(default=0)
    profileIconId = models.IntegerField(default=0)
    name = models.CharField(max_length=1000, default="")

기본정보만 담고 있으며, 여기에 있는 레코드로 프로필 정보를 업데이트 하도록 할 것이다. 외래키로 auth_user 모델과 연동한 상태이다.

내가 모은 모든 매치메타 데이터와 매치 데이터를 보관할 테이블 구조를 만들려고 한다.

class UserMatch(models.Model):
    # 'metadata'
    dataVersion = models.CharField(max_length=1000, default="")
    match_id = models.CharField(max_length=1000, default="")

    # 'info'
    endofGameResult = models.CharField(max_length=1000, default="")
    gameCreation = models.CharField(max_length=1000, default="")
    gameDuration = models.CharField(max_length=1000, default="")
    gameEndTimestamp = models.CharField(max_length=1000, default="")
    gameId = models.CharField(max_length=1000, default="")
    gameMode = models.CharField(max_length=1000, default="")
    gameName = models.CharField(max_length=1000, default="")
    mapId = models.CharField(max_length=1000, default="")

class Participant(models.Model):
    user_match = models.ForeignKey(UserMatch, on_delete=models.CASCADE)
    assists = models.IntegerField(default=0)
    bountyGold = models.IntegerField(default=0)
    controlWardsPlaced = models.IntegerField(default=0)
    damagePerMinute = models.FloatField(default=0)
    damageTakenOnTeamPercentage = models.FloatField(default=0)
    deathsByEnemyChamps = models.IntegerField(default=0)
    earlyLaningPhaseGoldExpAdvantage = models.IntegerField(default=0)
    epicMonsterKillsNearEnemyJungler = models.IntegerField(default=0)
    epicMonsterSteals = models.IntegerField(default=0)
    epicMonsterStolenWithoutSmite = models.IntegerField(default=0)
    firstTurretKilled = models.BooleanField(default=False)
    firstTurretKilledTime = models.FloatField(default=0)
    gameLength = models.FloatField(default=0)
    goldPerMinute = models.FloatField(default=0)
    immobilizeAndKillWithAlly = models.IntegerField(default=0)
    initialBuffCount = models.IntegerField(default=0)
    initialCrabCount = models.IntegerField(default=0)
    jungleCsBefore10Minutes = models.IntegerField(default=0)
    kTurretsDestroyedBeforePlatesFall = models.IntegerField(default=0)
    kda = models.FloatField(default=0)
    killAfterHiddenWithAlly = models.IntegerField(default=0)
    killParticipation = models.FloatField(default=0)
    killingSprees = models.IntegerField(default=0)
    killsNearEnemyTurret = models.IntegerField(default=0)
    killsOnOtherLanesEarlyJungleAsLaner = models.IntegerField(default=0)
    killsUnderOwnTurret = models.IntegerField(default=0)
    knockEnemyIntoTeamAndKill = models.IntegerField(default=0)
    laneMinionsFirst10Minutes = models.IntegerField(default=0)
    laningPhaseGoldExpAdvantage = models.IntegerField(default=0)
    legendaryCount = models.IntegerField(default=0)
    maxCsAdvantageOnLaneOpponent = models.IntegerField(default=0)
    maxLevelLeadLaneOpponent = models.IntegerField(default=0)
    moreEnemyJungleThanOpponent = models.FloatField(default=0)
    multikills = models.IntegerField(default=0)
    multikillsAfterAggressiveFlash = models.IntegerField(default=0)
    outerTurretExecutesBefore10Minutes = models.IntegerField(default=0)
    outnumberedKills = models.IntegerField(default=0)
    scuttleCrabKills = models.IntegerField(default=0)
    skillshotsDodged = models.IntegerField(default=0)
    soloKills = models.IntegerField(default=0)
    stealthWardsPlaced = models.IntegerField(default=0)
    takedownOnFirstTurret = models.IntegerField(default=0)
    takedowns = models.IntegerField(default=0)
    takedownsFirstXMinutes = models.IntegerField(default=0)
    teamDamagePercentage = models.FloatField(default=0)
    teleportTakedowns = models.IntegerField(default=0)
    turretPlatesTaken = models.IntegerField(default=0)
    turretTakedowns = models.IntegerField(default=0)
    visionScorePerMinute = models.FloatField(default=0)
    wardTakedowns = models.IntegerField(default=0)
    wardTakedownsBefore20M = models.IntegerField(default=0)
    wardsGuarded = models.IntegerField(default=0)
    championName = models.CharField(max_length=1000, default="")
    detectorWardsPlaced = models.IntegerField(default=0)
    deaths = models.IntegerField(default=0)
    doubleKills = models.IntegerField(default=0)
    kills = models.IntegerField(default=0)
    puuid = models.CharField(max_length=1000, default="")
    timePlayed = models.FloatField(default=0)
    tripleKills = models.IntegerField(default=0)
    totalDamageDealt = models.IntegerField(default=0)
    totalDamageDealtToChampions = models.IntegerField(default=0)
    totalDamageTaken = models.IntegerField(default=0)
    win = models.BooleanField(default=False)
    teamId = models.IntegerField(default=0)
    teamPosition = models.CharField(max_length=1000, default="")
    participantId = models.IntegerField(default=0)
    champExperience = models.IntegerField(default=0)
    champLevel = models.IntegerField(default=0)
    championId = models.IntegerField(default=0)
    # 'stats made by me
    
    dpt = models.FloatField(default=0)
    dpg = models.FloatField(default=0)
    ddpt = models.FloatField(default=0)
    dgpt = models.FloatField(default=0)

UserMatch에는 검색한 모든 매치가 들어가도록 하며, 해당 매치에 대한 메타 데이터를 담는다. Participant는 해당 매치 안에서 존재하는 개인 플레이어들에 대한 스텟 데이터이다. UserMatch와 일대다 구조의 참조관계이므로 외래키로 부모-자식 관계를 생성했다. 의미있는 데이터만 우선 먼저 쓰기로 하여 칼럼들을 작성했는데 너무 욕심이었는지 칼럼이 너무 많은 듯..

dpt, dpg, ddpt, dgpt는 내가 새로 만든 스텟이다. API제공 스텟을 활용해 만든 2차가공 스텟이다.

꽤 고심해서 만든 지표라 매우 소중

riotAPI를 활용한 파이썬 파일을 하나 따로 만들어 그곳에 기나긴 코드들을 정리할까 한다.

#riot_api.py

class RiotAPI:
    def __init__(self, API_KEY):
        self.API_KEY = API_KEY
        self.header = {"X-Riot-Token": API_KEY,
                       "count": "100",
                       }

    def get_puuid_from_summonerName(self, summonerName):
        url = f"https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-name/{summonerName}"
        response = requests.get(url, headers=self.header)
        return response.json()['puuid']
    
    def get_matchid_lst_from_puuid(self, puuid):
        url = f"https://asia.api.riotgames.com/lol/match/v5/matches/by-puuid/{puuid}/ids?"
        option = 'type=ranked&start=0&count=100'
        url_f = url + option
        response = requests.get(url_f, headers=self.header)
        return response.json()
    
    def get_match_matchId(self, matchId):
        url = f"https://asia.api.riotgames.com/lol/match/v5/matches/{matchId}"
        response = requests.get(url, headers=self.header)
        return response.json()             

    def get_match_Full(self, summonerName):
        puuid = self.get_puuid_from_summonerName(summonerName)
        matchid_lst = self.get_matchid_lst_from_puuid(puuid)
        match_lst = []
        for matchId in tqdm(matchid_lst):
            match_lst.append(self.get_match_matchId(matchId))
            time.sleep(0.1)
        return match_lst
    
    def authenticate_RiotID(self, riotID):
        try:
            self.get_puuid_from_summonerName(riotID)
            return True
        except:
            return False
        
    def get_user_profile(self, puuid):
        url = f"https://kr.api.riotgames.com/lol/summoner/v4/summoners/by-puuid/{puuid}"
        response = requests.get(url, headers=self.header)
        return response.json()
        

class MatchData:
    def __init__(self, metadata, info):
        self.dataVersion = metadata.get('dataVersion', '')
        self.match_id = metadata.get('matchId', '')
        self.endofGameResult = info.get('gameMode', '')
        self.gameCreation = info.get('gameCreation', '')
        self.gameDuration = info.get('gameDuration', '')
        self.gameEndTimestamp = info.get('gameEndTimestamp', '')
        self.gameId = info.get('gameId', '')
        self.gameMode = info.get('gameMode', '')
        self.gameName = info.get('gameName', '')
        self.mapId = info.get('mapId', '')

def update_matches(new_matches):
    for match in new_matches:
        metadata = match.get('metadata', {})
        info = match.get('info', {})
        match_data = MatchData(metadata, info)
        # 중복 여부를 확인하고 데이터베이스에 저장하는 로직을 수행합니다.
        try:
            match = UserMatch.objects.get(match_id=match_data.match_id)
        except UserMatch.DoesNotExist:
            # 데이터베이스에 존재하지 않는 경우 새로운 매치 데이터를 저장합니다.
            match = UserMatch.objects.create(
                dataVersion=match_data.dataVersion,
                match_id=match_data.match_id,
                endofGameResult=match_data.endofGameResult,
                gameCreation=match_data.gameCreation,
                gameDuration=match_data.gameDuration,
                gameEndTimestamp=match_data.gameEndTimestamp,
                gameId=match_data.gameId,
                gameMode=match_data.gameMode,
                gameName=match_data.gameName,
                mapId=match_data.mapId,
            )
            match.save()
            print("Match saved successfully {}".format(match_data.match_id))
            # 참가자 정보를 저장합니다.
            participants = info.get('participants', []) # lst
            for participant in participants:
                # 참가자 정보가 이미 존재하는지 확인합니다.
                try:
                    par_entry = Participant.objects.get(user_match=match, puuid=participant.get('puuid', ''))
                except Participant.DoesNotExist:
                    par_entry = Participant.objects.create(
                        user_match = match,
                        assists = participant.get('assists', 0),
                        bountyGold = participant.get("challenges").get('bountyGold', 0),
                        controlWardsPlaced = participant.get("challenges").get('controlWardsPlaced', 0),
                        damagePerMinute = participant.get("challenges").get('damagePerMinute', 0),
                        damageTakenOnTeamPercentage = participant.get("challenges").get('damageTakenOnTeamPercentage', 0),
                        deathsByEnemyChamps =  participant.get("challenges").get('deathsByEnemyChamps', 0),
                        earlyLaningPhaseGoldExpAdvantage = participant.get("challenges").get('earlyLaningPhaseGoldExpAdvantage', 0),
                        epicMonsterKillsNearEnemyJungler = participant.get("challenges").get('epicMonsterKillsNearEnemyJungler', 0),
                        epicMonsterSteals = participant.get("challenges").get('epicMonsterSteals', 0),
                        epicMonsterStolenWithoutSmite = participant.get("challenges").get('epicMonsterStolenWithoutSmite', 0),
                        firstTurretKilled = participant.get("challenges").get('firstTurretKilled', False),
                        firstTurretKilledTime = participant.get("challenges").get('firstTurretKilledTime', 0),
                        gameLength = participant.get("challenges").get('gameLength', 0),
                        goldPerMinute = participant.get("challenges").get('goldPerMinute', 0),
                        immobilizeAndKillWithAlly = participant.get("challenges").get('immobilizeAndKillWithAlly', 0),
                        initialBuffCount = participant.get("challenges").get('initialBuffCount', 0),
                        initialCrabCount = participant.get("challenges").get('initialCrabCount', 0),
                        jungleCsBefore10Minutes = participant.get("challenges").get('jungleCsBefore10Minutes', 0),
                        kTurretsDestroyedBeforePlatesFall = participant.get("challenges").get('kTurretsDestroyedBeforePlatesFall', 0),
                        kda = participant.get("challenges").get('kda', 0),
                        killAfterHiddenWithAlly = participant.get("challenges").get('killAfterHiddenWithAlly', 0),
                        killParticipation = participant.get("challenges").get('killParticipation', 0),
                        killingSprees = participant.get('killingSprees', 0),
                        killsNearEnemyTurret = participant.get("challenges").get('killsNearEnemyTurret', 0),
                        killsOnOtherLanesEarlyJungleAsLaner = participant.get("challenges").get('killsOnOtherLanesEarlyJungleAsLaner', 0),
                        killsUnderOwnTurret = participant.get("challenges").get('killsUnderOwnTurret', 0),
                        knockEnemyIntoTeamAndKill = participant.get("challenges").get('knockEnemyIntoTeamAndKill', 0),
                        laneMinionsFirst10Minutes = participant.get("challenges").get('laneMinionsFirst10Minutes', 0),
                        laningPhaseGoldExpAdvantage = participant.get("challenges").get('laningPhaseGoldExpAdvantage', 0),
                        legendaryCount = participant.get("challenges").get('legendaryCount', 0),
                        maxCsAdvantageOnLaneOpponent = participant.get("challenges").get('maxCsAdvantageOnLaneOpponent', 0),
                        maxLevelLeadLaneOpponent = participant.get("challenges").get('maxLevelLeadLaneOpponent', 0),
                        moreEnemyJungleThanOpponent = participant.get("challenges").get('moreEnemyJungleThanOpponent', 0),
                        multikills = participant.get("challenges").get('multikills', 0),
                        multikillsAfterAggressiveFlash = participant.get("challenges").get('multikillsAfterAggressiveFlash', 0),
                        outerTurretExecutesBefore10Minutes = participant.get("challenges").get('outerTurretExecutesBefore10Minutes', 0),
                        outnumberedKills = participant.get("challenges").get('outnumberedKills', 0),
                        scuttleCrabKills = participant.get("challenges").get('scuttleCrabKills', 0),
                        skillshotsDodged = participant.get("challenges").get('skillshotsDodged', 0),
                        soloKills = participant.get("challenges").get('soloKills', 0),
                        stealthWardsPlaced = participant.get("challenges").get('stealthWardsPlaced', 0),
                        takedownOnFirstTurret = participant.get("challenges").get('takedownOnFirstTurret', 0),
                        takedowns = participant.get("challenges").get('takedowns', 0),
                        takedownsFirstXMinutes = participant.get("challenges").get('takedownsFirstXMinutes', 0),
                        teamDamagePercentage = participant.get("challenges").get('teamDamagePercentage', 0),
                        teleportTakedowns = participant.get("challenges").get('teleportTakedowns', 0),
                        turretPlatesTaken = participant.get("challenges").get('turretPlatesTaken', 0),
                        turretTakedowns = participant.get("challenges").get('turretTakedowns', 0),
                        visionScorePerMinute = participant.get("challenges").get('visionScorePerMinute', 0),
                        wardTakedowns = participant.get("challenges").get('wardTakedowns', 0),
                        wardTakedownsBefore20M = participant.get("challenges").get('wardTakedownsBefore20M', 0),
                        wardsGuarded = participant.get("challenges").get('wardsGuarded', 0),
                        
                        championName = participant.get('championName', ''),
                        detectorWardsPlaced = participant.get('detectorWardsPlaced', 0),
                        deaths = participant.get('deaths', 0),
                        doubleKills = participant.get('doubleKills', 0),
                        kills = participant.get('kills', 0),
                        puuid = participant.get('puuid', ''),
                        timePlayed = participant.get('timePlayed', 0),
                        tripleKills = participant.get('tripleKills', 0),
                        totalDamageDealt = participant.get('totalDamageDealt', 0),
                        totalDamageDealtToChampions = participant.get('totalDamageDealtToChampions', 0),
                        totalDamageTaken = participant.get('totalDamageTaken', 0),
                        win = participant.get('win', False),
                        teamId = participant.get('teamId', 0),
                        teamPosition = participant.get('teamPosition', ''),
                        participantId = participant.get('participantId', -1),
                        champExperience = participant.get('champExperience', 0),
                        champLevel = participant.get('champLevel', 0),
                        championId = participant.get('championId', 0),

                        # totalDamageDealt / totalDamageTaken 
                        dpt = participant.get('totalDamageDealt', 0.0001) / participant.get('totalDamageTaken', 0.0001),
                        # damagePerMinute / goldPerMinute 
                        dpg = participant.get("challenges").get('damagePerMinute', 0.0001) / participant.get("challenges").get('goldPerMinute', 0.0001),
                        # totalTimeSpentDead / timePlayed
                        ddpt = participant.get('totalTimeSpentDead', 0.0001) / participant.get('timePlayed', 0.0001),
                        # skillshotsDodged / timePlayed
                        dgpt = participant.get("challenges").get('skillshotsDodged', 0.0001) / participant.get('timePlayed', 0.0001),
                                        )
                    # 데이터베이스에 저장합니다.
                    par_entry.save()
                    print("Participant saved successfully {}".format(participant.get('puuid', '')))
        else:
            participants = info.get('participants', []) # lst
            for participant in participants:
                # 참가자 정보가 이미 존재하는지 확인합니다.
                try:
                    par_entry = Participant.objects.get(user_match=match, puuid=participant.get('puuid', ''))
                except Participant.DoesNotExist:
                    par_entry = Participant.objects.create(
                        user_match = match,
                        assists = participant.get('assists', 0),
                        bountyGold = participant.get("challenges").get('bountyGold', 0),
                        controlWardsPlaced = participant.get("challenges").get('controlWardsPlaced', 0),
                        damagePerMinute = participant.get("challenges").get('damagePerMinute', 0),
                        damageTakenOnTeamPercentage = participant.get("challenges").get('damageTakenOnTeamPercentage', 0),
                        deathsByEnemyChamps =  participant.get("challenges").get('deathsByEnemyChamps', 0),
                        earlyLaningPhaseGoldExpAdvantage = participant.get("challenges").get('earlyLaningPhaseGoldExpAdvantage', 0),
                        epicMonsterKillsNearEnemyJungler = participant.get("challenges").get('epicMonsterKillsNearEnemyJungler', 0),
                        epicMonsterSteals = participant.get("challenges").get('epicMonsterSteals', 0),
                        epicMonsterStolenWithoutSmite = participant.get("challenges").get('epicMonsterStolenWithoutSmite', 0),
                        firstTurretKilled = participant.get("challenges").get('firstTurretKilled', False),
                        firstTurretKilledTime = participant.get("challenges").get('firstTurretKilledTime', 0),
                        gameLength = participant.get("challenges").get('gameLength', 0),
                        goldPerMinute = participant.get("challenges").get('goldPerMinute', 0),
                        immobilizeAndKillWithAlly = participant.get("challenges").get('immobilizeAndKillWithAlly', 0),
                        initialBuffCount = participant.get("challenges").get('initialBuffCount', 0),
                        initialCrabCount = participant.get("challenges").get('initialCrabCount', 0),
                        jungleCsBefore10Minutes = participant.get("challenges").get('jungleCsBefore10Minutes', 0),
                        kTurretsDestroyedBeforePlatesFall = participant.get("challenges").get('kTurretsDestroyedBeforePlatesFall', 0),
                        kda = participant.get("challenges").get('kda', 0),
                        killAfterHiddenWithAlly = participant.get("challenges").get('killAfterHiddenWithAlly', 0),
                        killParticipation = participant.get("challenges").get('killParticipation', 0),
                        killingSprees = participant.get('killingSprees', 0),
                        killsNearEnemyTurret = participant.get("challenges").get('killsNearEnemyTurret', 0),
                        killsOnOtherLanesEarlyJungleAsLaner = participant.get("challenges").get('killsOnOtherLanesEarlyJungleAsLaner', 0),
                        killsUnderOwnTurret = participant.get("challenges").get('killsUnderOwnTurret', 0),
                        knockEnemyIntoTeamAndKill = participant.get("challenges").get('knockEnemyIntoTeamAndKill', 0),
                        laneMinionsFirst10Minutes = participant.get("challenges").get('laneMinionsFirst10Minutes', 0),
                        laningPhaseGoldExpAdvantage = participant.get("challenges").get('laningPhaseGoldExpAdvantage', 0),
                        legendaryCount = participant.get("challenges").get('legendaryCount', 0),
                        maxCsAdvantageOnLaneOpponent = participant.get("challenges").get('maxCsAdvantageOnLaneOpponent', 0),
                        maxLevelLeadLaneOpponent = participant.get("challenges").get('maxLevelLeadLaneOpponent', 0),
                        moreEnemyJungleThanOpponent = participant.get("challenges").get('moreEnemyJungleThanOpponent', 0),
                        multikills = participant.get("challenges").get('multikills', 0),
                        multikillsAfterAggressiveFlash = participant.get("challenges").get('multikillsAfterAggressiveFlash', 0),
                        outerTurretExecutesBefore10Minutes = participant.get("challenges").get('outerTurretExecutesBefore10Minutes', 0),
                        outnumberedKills = participant.get("challenges").get('outnumberedKills', 0),
                        scuttleCrabKills = participant.get("challenges").get('scuttleCrabKills', 0),
                        skillshotsDodged = participant.get("challenges").get('skillshotsDodged', 0),
                        soloKills = participant.get("challenges").get('soloKills', 0),
                        stealthWardsPlaced = participant.get("challenges").get('stealthWardsPlaced', 0),
                        takedownOnFirstTurret = participant.get("challenges").get('takedownOnFirstTurret', 0),
                        takedowns = participant.get("challenges").get('takedowns', 0),
                        takedownsFirstXMinutes = participant.get("challenges").get('takedownsFirstXMinutes', 0),
                        teamDamagePercentage = participant.get("challenges").get('teamDamagePercentage', 0),
                        teleportTakedowns = participant.get("challenges").get('teleportTakedowns', 0),
                        turretPlatesTaken = participant.get("challenges").get('turretPlatesTaken', 0),
                        turretTakedowns = participant.get("challenges").get('turretTakedowns', 0),
                        visionScorePerMinute = participant.get("challenges").get('visionScorePerMinute', 0),
                        wardTakedowns = participant.get("challenges").get('wardTakedowns', 0),
                        wardTakedownsBefore20M = participant.get("challenges").get('wardTakedownsBefore20M', 0),
                        wardsGuarded = participant.get("challenges").get('wardsGuarded', 0),
                        
                        championName = participant.get('championName', ''),
                        detectorWardsPlaced = participant.get('detectorWardsPlaced', 0),
                        deaths = participant.get('deaths', 0),
                        doubleKills = participant.get('doubleKills', 0),
                        kills = participant.get('kills', 0),
                        puuid = participant.get('puuid', ''),
                        timePlayed = participant.get('timePlayed', 0),
                        tripleKills = participant.get('tripleKills', 0),
                        totalDamageDealt = participant.get('totalDamageDealt', 0),
                        totalDamageDealtToChampions = participant.get('totalDamageDealtToChampions', 0),
                        totalDamageTaken = participant.get('totalDamageTaken', 0),
                        win = participant.get('win', False),
                        teamId = participant.get('teamId', 0),
                        teamPosition = participant.get('teamPosition', ''),
                        participantId = participant.get('participantId', -1),
                        champExperience = participant.get('champExperience', 0),
                        champLevel = participant.get('champLevel', 0),
                        championId = participant.get('championId', 0),
                        
                        # totalDamageDealt / totalDamageTaken 
                        dpt = participant.get('totalDamageDealt', 0.0001) / participant.get('totalDamageTaken', 0.0001),
                        # damagePerMinute / goldPerMinute 
                        dpg = participant.get("challenges").get('damagePerMinute', 0.0001) / participant.get("challenges").get('goldPerMinute', 0.0001),
                        # totalTimeSpentDead / timePlayed
                        ddpt = participant.get('totalTimeSpentDead', 0.0001) / participant.get('timePlayed', 0.0001),
                        # skillshotsDodged / timePlayed
                        dgpt = participant.get("challenges").get('skillshotsDodged', 0.0001) / participant.get('timePlayed', 0.0001),
                                        )
                    # 데이터베이스에 저장합니다.
                    par_entry.save()
                    print("Participant saved successfully {}".format(participant.get('puuid', '')))

이렇게 세팅을 끝내고, view클래스 작업을 해준다. 이는 update엔드포인트에 연결될 것이다. post에서 우선 기본 프로필을 업데이트하고, 그 다음 매치를 가져온다. api를 가져올 때 걸리는 시간이 꽤 되므로 이를 어떻게 단축시킬지 후에 고민해봐야겠다. 아마 대형 전적검색 사이트의 경우 게임사와 제휴하여 전문용 APIKEY를 받아 속도면에서 우월할 것이긴 하지만..

class UpdateView(APIView):
    def post(self, request):
        userId = request.data.get('userId')    
        user_instance = User.objects.get(username=userId)
        ra = RiotAPI(RIOTAPIKEY)
        try:
            # 이미 존재하는 레코드를 가져옵니다.
            entry = UserRiot.objects.get(user=user_instance)
            update = ra.get_user_profile(entry.riot_puuid)
            
        except UserRiot.DoesNotExist:
            return Response({'error': '등록된 소환사명이 없습니다.'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            entry.revision_date = update['revisionDate']
            entry.summonerLevel = update['summonerLevel']
            entry.profileIconId = update['profileIconId']
            entry.name = update['name']
            entry.save()

        # 유저 매치 정보 업데이트
        entry_riot = UserRiot.objects.get(user=user_instance)
        match_lst = ra.get_match_Full(entry_riot.riot_id)
        # 매치정보 데이터 베이스에 입력
        update_matches(match_lst)
        return Response({'message': '소환사 정보 업데이트 성공',
                         'summonerLevel': update['summonerLevel'],
                            'profileIconId': update['profileIconId'],
                            'name': update['name']}, status=status.HTTP_201_CREATED)

하나의 계졍에 대한 100개의 매치 데이터를 넣었다. 100개의 매치데이터를 생성하면 10명이 플레이어니 1000개의 Participant테이블 안의 레코드가 생성될 것을 기대.

근데 문제가 10개씩 빠지는 문제가 발생해서 확인해보니, 게임이 비정상적으로 끝났을 때(다시하기 같은) 데이터가 정상적으로 들어오지 않아 데이터베이스화가 불가능 한 것으로 보였다.

기존 전적검색 사이트에서 참고하고자 확인해보니, 다시하기 기록같은 경우는 일시적으로 존재했다가 추후에 사라진다.

profile
자바집사의 거북이 수련법

0개의 댓글