API 를 호출 하기 위해 request 를 하다 보면 언젠가 python requests.exceptions.ConnectionError 오류가 발생 할 수 있습니다.
이를 막고자 계속 실행하기 위해서는 대책이 필요한데요
저는 Max retries exceeded with url 오류 발생 시 urlopen 을 활용 하여 끊김 없이 데이터를 불러 오도록 만들어 보았습니다.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import json | |
import requests | |
from urllib.request import urlopen | |
# 저는 deribit 을 활용하고 있어서 아래 사이트로 예시를 들었습니다. | |
url = 'https://www.deribit.com/api/v2/public/get_last_trades_by_currency?currency=BTC' | |
while(True): | |
# 기존 request 로 가져오는 방식에서 아래 except 를 추가해서 urlopen 으로 크롤링 하여 가져오는 방법을 추가 | |
try: | |
res = requests.get(url) | |
# requests 오류 시 아래 urlopen 을 사용 하여 data 불러 오는데 끊김이 없도록 실행 | |
except: | |
page = urlopen(url) | |
# bytes to string | |
doc = page.read().decode('utf-8') | |
# string to dictionary | |
dic = json.loads(doc) | |
result_dict = dic['result']['trades'] | |
# 오류가 없을 경우 | |
else: | |
if res.status_code == 200: | |
result_dict = json.loads(res.text)['result']['trades'] | |
else: | |
print(res.status_code) | |
continue | |
for i in result_dict: | |
... |
잘못되었거나 궁금하신 것 있으면 답글 부탁 드립니다.
감사합니다.
'개발 > Python' 카테고리의 다른 글
E: Unable to locate package python3-pip 오류 해결 (0) | 2020.05.29 |
---|---|
[python] deribit 거래소 api v2 활용하여 거래하기 (4) | 2020.04.01 |
python multiple file upload 파이썬 파일 다중 업로드 (0) | 2020.03.10 |
python 죽은 프로그램 다시 실행 시키는 os.execl 사용법 (0) | 2020.02.27 |
Python Jupyter notebook에서 tqdm 으로 for 문 진행 상황 확인하기 (0) | 2019.12.09 |