3-1. 축제 및 행사정보 코드

투어하냥💜·2019년 12월 11일
0

SKT NUGU Project

목록 보기
4/10

2.2 에서 말한 축제 및 행사정보 데이터셋을 불러오는 코드를 작성하겠다. 코드진행순서는 다음과 같다.
1. 필요한 module
2. conent함수
3. action함수


1. 필요한 module

import urllib 
from urllib.request import urlopen
import json
  • import urllib : URL처리에 관련된 module을 모아놓은 package로 tour api를 불러와 처리하는 데 사용한다.
  • from urllib.request import urlopen : urllib package의 request module에서 urlopen함수를 가져온다. 그 함수를 통해 url처리에 사용한다.
  • import json: 앞서 국내관광정보서비스를 tour api에서 json형식으로 호출하였다. 따라서 json형식으로 데이터를 응답받기에 이를 처리하는데 사용한다.
    • json: 속성-값 쌍 또는 키-값 쌍으로 이루어진 데이터오브젝트를 전달하기위해 인간이 읽을수있는 텍스트사용하는 개방형표준포맷

2. content 함수

def content(sigungu, start, end):
    sigunguCode = sigungu
    eventStartDate = start
    eventEndDate = end
    content_id = [] 
    content_title = []

content함수는 sigungu, start, end변수를 parameter(매개변수)로 사용한다.
sigungu: 외부에서 입력받은 시군구 코드
start,end: 검색하고자 하는 날짜
매개변수 sigungu,start,end를 각각 sigunguCode변수, eventStartDate변수, eventEndDate변수 에 초기화한다.

ServiceKey = "ServiceKey"
url_s = "http://api.visitkorea.or.kr/openapi/service/rest/KorService/searchFestival?ServiceKey=" + ServiceKey + "&MobileOS=ETC&MobileApp=TourAPI3.0_Guide&areaCode=1&numOfRows=3&listYN=Y&arrange=B&_type=json"

url_search = url_s + "&sigunguCode=" + str(sigunguCode) + "&eventStartDate=" + str(
        eventStartDate) + "&eventEndDate=" + str(eventEndDate)

다음 코드는 사용자가 요청하는 날짜와 장소에 해당하는 축제공연행사 정보검색을 위해 사용되는 방식이다.
url을 하나씩 살펴보면
"areaCode=1"은 서울특별시를 나타내고, "numOfRow=3"은 한페이지 결과수로 총 3개의 검색된 정보를 가져온다.
"listYN=Y"는 list형태로 결과를 나타내고, "arrange=B"는 인기순서대로 정렬을 나타낸다.
"_type=json"은 json형식으로 데이터 요청함을 의미한다.

sigunguCode변수, eventStartDate변수, eventEndDate변수을 url_s변수에 추가하여 구체적인 장소와 날짜를 추가하여 정보를 검색한다.

request = urllib.request.Request(url_search)
response = urllib.request.urlopen(request)
rescode = response.getcode()

urllib.request.urlopen은 URL을 여는 함수로 URL열기에 성공하면 getcode함수를 통해 200을 받는다.
따라서 200은 HTTP상태코드로 웹서버가 요청을 제대로 처리함을 의미한다.

 if (rescode == 200):
        response_body = response.read() 
        data = json.loads(response_body.decode('utf-8')) 
        global data_num #data_num은 축제의 개수를 받을 변수
        data_num = data["response"]["body"]["totalCount"] 
        
        if (data_num == 0):  #검색되는 축제가 없을때
            return ("null") 

        elif (data_num == 1):
            for i in range(0, 1):  # 검색된 축제가 1개일때
                content_title.append(data["response"]["body"]["items"]["item"]['title']) 
                content_id.append(data["response"]["body"]["items"]["item"]['contentid'])

        elif (data_num > 3): # 검색된 축제가 3개초과일때 차례대로 3개의 축제만 처리.
            for i in range(0, 3):  
                content_title.append(data["response"]["body"]["items"]["item"][i]['title'])
                content_id.append(data["response"]["body"]["items"]["item"][i]['contentid'])
        else:
            for i in range(data_num):  # 검색된 축제가 2개 혹은 3개일때 
                content_title.append(data["response"]["body"]["items"]["item"][i]['title'])
                content_id.append(data["response"]["body"]["items"]["item"][i]['contentid'])
    else:
        print("Error Code:" + rescode)
  • data변수는 json decoding을 하는 json.loads() method사용하여 response가 url을 불러서 받은 json문자열을 python type으로 변경한다.
  • 축제의 개수를 나타내는 data_num변수에 total count를 초기화한다.
    • 검색되는 축제가 없으면 null return한다.
    • 검색되는 축제가 있으면 그 개수만큼 append함수를 통해 축제의 title와 contentid를 각각 content_titlecontent_id에 추가한다.
  • URL열기에 실패하면 error code출력한다.
url =" http://api.visitkorea.or.kr/openapi/service/rest/KorService/detailIntro?ServiceKey=" + ServiceKey+ "&contentTypeId=15&MobileOS=ETC&MobileApp=TourAPI3.0_Guide&introYN=Y&_type=json"

위 코드에서 불러온 content id를 사용하여 소개정보를 해당하는 행사의 상세정보를 가져오기위해 사용되는 방식이다.

content_num = data_num

content_id_detail = []
url_detail = []
request_detail = []
response_detail = []
rescode_detail = [0, 0, 0]
response_body_detail = []
data_detail = [] 
place = [] #축제및행사 상세장소
time = [] #축제및행사 공연시간
cost = [] #축제및행사 이용요금

    if content_num == 0: #검색된 축제가 0개인 경우
        content_title.append("null")
        place.append("null")
        time.append("null")
        cost.append("null")
    elif content_num > 3: #검색된 축제가 3개 초과일 경우 차례대로 3개의 축제만 처리
        for a in range(0, 3):
            url_detail.append(url + "&contentId=" + str(content_id[a]))
            request_detail.append(urllib.request.Request(url_detail[a]))
            response_detail.append(urllib.request.urlopen(request_detail[a]))
            response_body_detail.append(response_detail[a].read())
            data_detail.append(json.loads(response_body_detail[a].decode('utf-8')))
            place.append(data_detail[a]['response']['body']['items']['item']['eventplace'])
            time.append(data_detail[a]['response']['body']['items']['item']['playtime'])
            cost.append(data_detail[a]['response']['body']['items']['item']['usetimefestival'])

    else: #검색된 축제가 2개 혹은 3개인 경우
        for a in range(content_num):
            url_detail.append(url + "&contentId=" + str(content_id[a]))
            request_detail.append(urllib.request.Request(url_detail[a]))
            response_detail.append(urllib.request.urlopen(request_detail[a]))
            response_body_detail.append(response_detail[a].read())
            # print(response_body_detail[a].decode('utf-8'))
            data_detail.append(json.loads(response_body_detail[a].decode('utf-8')))
            place.append(data_detail[a]['response']['body']['items']['item']['eventplace'])
            time.append(data_detail[a]['response']['body']['items']['item']['playtime'])
            cost.append(data_detail[a]['response']['body']['items']['item']['usetimefestival'])

    return content_title, place, time, cost

전반적인 진행방식은 앞서 말한 code 진행방식과 비슷하다.

  • 검색되는 축제가 없으면 : content_title, place, time, cost에 null추가한다.
  • 검색되는 축제가 있으면 : 그 개수만큼 append함수를 통해 축제의 제목, 장소, 시간, 요금을 각각 content_title, place, time, cost에 추가한다.
  • content함수의 출력할 정보인 content_title,place,time,cost를 return으로 반환한다.

3. action함수

content 함수에서 return 한 값인 content_title, place, time, cost를 매개변수(parameter)로 사용하여 action함수를 진행한다.
action함수에서는 dict(zip[키1,키2],[값1,값2]))을 통해 키=값 형식으로 딕셔너리를 만든다.
따라서 number, title, place, time, cost 각각의 key들을 각각의 value 값과 matching시킨다.
만들어진 딕셔너리를 arr변수에 추가하여 마지막에 함수 return값으로 사용한다.

def action(c):
    keys = ['number', 'title', 'place', 'time', 'cost']
    arr = []
    if data_num == 0: #content함수에서 받아온 축제의 개수가 0인 경우
        return arr

    elif data_num == 1: #content함수에서 받아온 축제의 개수가1개인 경우
        values = ["1", c[0], c[1], c[2], c[3]]
        A = dict(zip(keys, values))
        arr.append(A)
        return arr

    elif data_num == 2: #content함수에서 받아온 축제의 개수가 2개인 경우
       values_1 = ["1", c[0][0], c[1][0], c[2][0], c[3][0]]
        values_2 = ["2", c[0][1], c[1][1], c[2][1], c[3][1]]
        A = dict(zip(keys, values_1))
        B = dict(zip(keys, values_2))
        arr.append(A)
        arr.append(B)
        return arr

    else: #content함수에서 받아온 축제의 개수가 3개인 경우
        values_1 = ["1", c[0][0], c[1][0], c[2][0], c[3][0]]
        values_2 = ["2", c[0][1], c[1][1], c[2][1], c[3][1]]
        values_3 = ["3", c[0][2], c[1][2], c[2][2], c[3][2]]
        A = dict(zip(keys, values_1))
        B = dict(zip(keys, values_2))
        C = dict(zip(keys, values_3))
        arr.append(A)
        arr.append(B)
        arr.append(C)
        return arr

이렇게 축제 및 행사정보 를 tour api에서 가져오는 코드는 완성이 되었다.
앞서 불러온 내용 외에도 여러 카테고리의 정보를 불러올 수 있으니 다양하게 시도해 볼 수 있다.

profile
TourHanyang

0개의 댓글