여러 건의 requests 모듈로 처리하던 것을 aiohttp 코드로 바꾸고 싶어요.

조회수 592회
 position_count = []
    for matchid in matchid_list:
        url = "https://api.***.com/matches/" + matchid + "?apikey=***"
        temp_dict = requests.get(url).json()
        try:
            for i in range(0, 10):
                if user == temp_dict['players'][i]['nickname']:
                    count = temp_dict['players'][i]['position']['name']
                    position_count.append(count)
        except IndexError:
            pass
    position_count2 = Counter(position_count).most_common()

약 100개의 json 파일을 불러와서 dict 형태에서 원하는 값을 찾아 뽑아내는 코드인데요, 이를 비동기식으로 처리하면 더 빠른 처리가 가능하다고 해서 aiohttp라는 모듈을 알게 되었습니다.

   position_count = []
    async def get_position(matchid: str):
        async with aiohttp.request('GET', 'https://api.***.com/matches/'+matchid+'?apikey=***') as resp:
            print(resp.json)

    tasks = [get_position(matchid) for matchid in matchid_list]    
    asyncio.run(asyncio.wait(tasks))

    position_count2 = Counter(position_count).most_common()

resp.json이 실행되면 제대로 된 url을 보내고 있음을 확인할 수 있습니다. 그러나 각각의 json을 임의의 temp_json이라는 변수에 넣어 dict 형태로 받아 indexing하는 부분에서 막힘이 있어 질문드립니다. 감사합니다.

  • (•́ ✖ •̀)
    알 수 없는 사용자

1 답변

  • 비동기로 한다는 것은 순서가 중요하지 않다는 의미일겁니다.

    질문자의 코드를 최대한 변경하지 않는 선에서 비동기 효과를 보자고 한다면 get_position 함수를 아래와 같이 변경하는 겁니다.

    Counter 의 결과를 다 받아내고 _c로 후처리를 이어서 하면 됩니다.

    _c = []
    async def get_position(matchid: str, c: List):  # c는 Counter(position_count)  저장할 컨테이너
        ...
        ...
    
        c.extends(Counter(position_count).most_common())
    
    ...
    ...
    tasks = [get_position(matchid, _c) for matchid in matchid_list] 
    
    • _c와 c의 차이점이 무엇인지, 생략하신 부분에 대한 코드도 조금만 더 자세히 적어주실 수 있을까요? async def 안에 Counter의 결과를 받아내는 부분까지 모두 집어넣는건가요? 알 수 없는 사용자 2019.8.20 00:06
    • 그렇죠 질문자께서 작성한 코드는 두가지 작업이 한번에 묶여있으므로 코루틴으로 처리할 부분(비동기적으로)을 나눠서 처리하고 그 결과만 집계하는 겁니다. _c는 전역변수라 _를 붙였고 tasks = [get_position(matchid, _c) for matchid in matchid_list] 에서 전달하고 있습니다. get_position 에서는 _c 가 c 입니다. 결과를 저장하기 위한 용도입니다. 즉 비동기적으로 처리한 모든 결과가 _c에 저장됩니다. 정영훈 2019.8.20 12:22

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)