본문 바로가기

Coding/Riot API를 사용하여 lolchess.gg 클론 코딩

라이엇 api를 사용하여 TFT(롤토체스) 데이터 수집 -6

1.한국 챌린져 큐의 최근  게임 가져오기

 

1-5-2) get_match_history(), match_v1_get_match_history()

 

 

match_hx 는 이미 저장 되어있는 match_hx.json에서 가져온 파일입니다.

중간에 코드가 끊길 경우를 대비하여서 

 

match_v1_get_match_history에서 중간 저장 하는 코드가 있으며,

이때 사용하기 위해 해당 함수에도 인자가 들어있습니다.

def get_match_historys(a, match_hx):
    match_hx = match_hx
    print(" start - get match historys")
    start = time.time()
    total_num = len(a)
    global new_list
    new_list = []
    for i, matchid in enumerate(a):
        try:
            match_hx = match_v1_get_match_history(matchid, match_hx)
            new_list.append(matchid)
            print(f"success get hx - location : {i}/{total_num}")

        except Exception:
            print(f"error get hx - location : {i}")
            pass

    end = time.time()

    print(f"success - match_history : {end - start:.2f} sec")

    return match_hx

 

while True 구문이 중간 저장하는 파트입니다.

해당 루프 까지의 saved_matchids 와 matchhx를 새로 저장하는 부분입니다.

def match_v1_get_match_history(matchid, match_hx):

    url = f"https://asia.api.riotgames.com/tft/match/v1/matches/{matchid}"
    r = get_r(url)
    if r.status_code == 200:
        save_saved_matchids(new_list)

    elif r.status_code == 429 or r.status_code == 502 or r.status_code == 503:
        if r.status_code == 429:
            print("api cost full : infinite loop start")
        elif r.status_code == 502:
            print(" 502 error : infinite loop start")
        elif r.status_code == 503:
            print(" 503 error : infinite loop start")
        start_time = time.time()

        i = 1
        while True:
            if i == 1:
                save_matchhx(match_hx)
                save_saved_matchids(new_list)
                print("Saved for error")

            if r.status_code == 429 or r.status_code == 502 or r.status_code == 503:
                print(f"try 10 seconds wait time: {i} loops, {r.status_code} error")
                time.sleep(10)
                i = i + 1
                r = get_r(url)

            elif r.status_code == 200:
                print("total wait time :", time.time() - start_time)
                break
    else:
        print(r.status_code)
        print(f"error : {matchid}")
        raise Exception("No match history !!")

    match_hx.append(r.json())
    return match_hx​
def save_matchhx(match_hx):
    file_path = "data/match_hx.json"
    with open(file_path, "w") as f:
        json.dump(match_hx, f)
def save_saved_matchids(new_data):
    if os.path.isfile("data/matchids_saved.csv"):
        saved_matchids_df = pd.read_csv("data/matchids_saved.csv")
        a = set(saved_matchids_df["matchid"].to_list())
        new_matchids = list(a | set(new_data))
    else:
        print("No saved file!?")
        new_matchids = []
    matchids_df = pd.DataFrame(new_matchids, columns=["matchid"])
    matchids_df.to_csv("data/matchids_saved.csv", index=False, encoding="utf-8-sig")

 

 

 

실행 되었을 때 의 터미널 사진입니다. 해당 루프에 저장 후 대략 2분정도 기다리고 100개 가져오네요

api cost 때문에 100경기씩 가져오기 때문에 정말 오래 걸립니다..ㅠ

 

matchids_saved 가 루프마다 업데이트 될 것이고,
match_hx.json으로 match_hx를 저장하는데 까지 성공했습니다!