python
datetime
strftime
timedelta
api 호출
파일쓰기, 플러그인
schedul, time module
Logstash에서 HTTP 요청으로 데이터를 수집하려 했다..🥲
그런데 API 호출이 안되기도 하고 매일 API 주소를 바꿔야 해서 Python을 사용하기로 했다.
Schedule 모듈을 통해 매일 함수 실행import datetime as datetime
today = datetime.datetime.now()
todayYmd = today.strftime("%Y%m%d")
ocrnYmd = str(int(today_ymd)-1)
datetime모듈을 통해 오늘 날짜를 구하고 하루 빼주었다.또는 아래 방식으로 해도 된다.
from datetime import date, timedelta
today = date.today()
yesterday = date.today() - timedelta(1)
ocrnYmd = yesterday.strftime("%Y%m%d")
import requests
serviceKey = "{공공데이터포털에서 받은 인증키}"
pageNo = "1" # 페이지 번호
numOfRows = "100" # 한 페이지 결과 수
resultType = "json" # 결과 형식
ocrn_ymd = ocrnYmd # 발생 일자
url = "https://apis.data.go.kr/1661000/FireInformationService/getOcBysidoFireSmrzPcnd?serviceKey={}&pageNo={}&numOfRows={}&resultType={}&ocrn_ymd={}".format(serviceKey, pageNo, numOfRows, resultType, ocrn_ymd)
responses = requests.get(url).json()['response']['body']['items']['item']
import json
with open(file_path, 'a') as file:
json.dumps(responses)
a를 사용해준다.json 모듈을 사용해준다.with open(file_path, 'a') as file:
for response in responses:
response['newYmd'] = datetime.datetime.strptime(response['ocrnYmd'], '%Y%m%d').strftime("%Y-%m-%d")
json.dumps(responses)
Date형식으로 받아와야 하는데 str형식으로 받아와서 사용하기 불편했다.Date형식으로 저장해줬다.index pattern에서 새로고침을 해주면 적용이 된다.with open(file_path, 'a') as file:
for response in responses:
response['newYmd'] = datetime.datetime.strptime(response['ocrnYmd'], '%Y%m%d').strftime("%Y-%m-%d")
response_json = json.dumps(response)
file.write(response_json)
file.write('\n')
import schedule, time
schedule.every(1).day.at("00:05").do(write_file)
while True:
schedule.run_pending()
time.sleep(1)
Schedule 모듈을 통해 매일 자정이 지나면 API 호출과 JSON 파일로 저장하도록 함수를 실행시켜준다.import datetime as datetime
import json, requests
import schedule, time
def write_file():
today = datetime.datetime.now()
serviceKey = "{공공데이터포털에서 받은 인증키}"
pageNo = "1" # 페이지 번호
numOfRows = "100" # 한 페이지 결과 수
resultType = "json" # 결과 형식
today_ymd = today.strftime("%Y%m%d")
ocrn_ymd = str(int(today_ymd)-1)
url = "https://apis.data.go.kr/1661000/FireInformationService/getOcBysidoFireSmrzPcnd?serviceKey={}&pageNo={}&numOfRows={}&resultType={}&ocrn_ymd={}".format(serviceKey, pageNo, numOfRows, resultType, ocrn_ymd)
responses = requests.get(url).json()['response']['body']['items']['item']
file_path = "{파일을 저장할 위치}/{파일명}.json"
with open(file_path, 'a') as file:
for response in responses:
response['newYmd'] = datetime.datetime.strptime(response['ocrnYmd'], '%Y%m%d').strftime("%Y-%m-%d")
response_json = json.dumps(response)
file.write(response_json)
file.write('\n')
schedule.every(1).day.at("00:05").do(write_file)
while True:
schedule.run_pending()
time.sleep(1)
{
"sidoNm": "\uc11c\uc6b8\ud2b9\ubcc4\uc2dc", // 시도명
"flsrpPrcsMnb": 22, // 오보처리건수
"slfExtshMnb": 3, // 자체진화건수
"fireRcptMnb": 46, // 화재접수건수
"stnEndMnb": 14, // 상황종료건수
"ocrnYmd": "20230215", // 발생일자
"falsDclrMnb": 0, // 허위신고건수
"newYmd": "2023-02-15"
}
시도명은 한글로 출력된다.input {
file {
path => "{파일 경로}/{파일명}.json"
start_position => "beginning"
}
}
sincedb를 통하여 어디까지 읽었는지 감지하고 그 이후부터 읽어온다.filter {
json {
source => "message"
}
mutate {
rename => {
"sidoNm" => "시도명"
"flsrpPrcsMnb" => "오보처리건수"
"slfExtshMnb" => "자체진화건수"
"fireRcptMnb" => "화재접수건수"
"stnEndMnb" => "상황종료건수"
"newYmd" => "발생일자"
"falsDclrMnb" => "허위신고건수"
}
remove_field => [
"_type",
"@version",
"tags",
"@timestamp",
"path",
"message",
"host",
"ocrnYmd"
]
}
}
rename을 사용하여 변경해주었다.remove_field를 통해 지워주었다.output {
stdout { }
elasticsearch {
hosts => ["http://localhost:9200"]
index => "fire"
}
}
stdout으로 출력해주었다.elasticsearch로도 전송해주었다.input {
file {
path => "C:/Users/ibricks/Downloads/esk/logstash-7.10.2/files/fire3.json"
start_position => "beginning"
}
}
filter {
json {
source => "message"
}
mutate {
rename => {
"sidoNm" => "시도명"
"flsrpPrcsMnb" => "오보처리건수"
"slfExtshMnb" => "자체진화건수"
"fireRcptMnb" => "화재접수건수"
"stnEndMnb" => "상황종료건수"
"newYmd" => "발생일자"
"falsDclrMnb" => "허위신고건수"
}
remove_field => [
"_type",
"@version",
"tags",
"@timestamp",
"path",
"message",
"host",
"ocrnYmd"
]
}
}
output {
stdout { }
elasticsearch {
hosts => ["http://localhost:9200"]
index => "fire"
}
}