API 를 호출 하기 위해 request 를 하다 보면 언젠가 python requests.exceptions.ConnectionError 오류가 발생 할 수 있습니다.

이를 막고자 계속 실행하기 위해서는 대책이 필요한데요

저는 Max retries exceeded with url 오류 발생 시 urlopen 을 활용 하여 끊김 없이 데이터를 불러 오도록 만들어 보았습니다.

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:
...
view raw urlopen.py hosted with ❤ by GitHub

잘못되었거나 궁금하신 것 있으면 답글 부탁 드립니다.

감사합니다.

파이썬과 html 을 활용해서 간단하게 만들어 보았습니다.

집에 남는 PC를 삼바 서버로 활용하고 있어 외부에서도 삼바서버에 업로드 할 수 있게 만들어 보았습니다.

안되거나 궁금한 사항 있으시면 댓글 부탁 드립니다. 

 

1. python

from flask import Flask, render_template, request
from werkzeug.utils import secure_filename
app = Flask(__name__)
@app.route('/')
def render_file():
return render_template('upload.html')
@app.route('/fileUpload', methods = ['GET', 'POST'])
def upload_file():
if request.method == 'POST':
files = request.files
print(type(files))
print('----------')
for f in files.to_dict(flat=False)['filename[]']:
f.save('/opt/folder/aaa/'+secure_filename(f.filename))
print(f.filename)
return render_template('success.html')
if __name__ == '__main__':
app.run(host='192.168.0.112', port=8000, debug = True)
view raw file_upload.py hosted with ❤ by GitHub

2. html

<html>
<head>
<meta name="viewport" content="width=device-width,initial-scale=1.0,minimum-scale=1.0,maximum-scale=1.0">
</head>
<body>
<div style="width:80%;text-align:center;margin:30px auto;">
<form action = "http://192.168.0.112:8000/fileUpload" method = "POST" enctype = "multipart/form-data">
<input style="width:80%;padding-bottom:20px;height:22%" multiple="multiple" type = "file" name = "filename[]" />
<input style="width:80%;height:10%" type = "submit" />
</form>
</div>
</body>
</html>
view raw upload.html hosted with ❤ by GitHub

코인 거래소 API 를 websocket 으로 받오는 중에 프로세스가 자꾸 죽어서 아래와 같은 해결 방법을 아래와 같이 찾았습니다. 내용을 더 찾아보고 싶으신 분은 https://www.programcreek.com/python/example/7545/os.execl 여기서 확인 하시면 됩니다 !

사용법은 간단하게 작성 하였습니다. 메인 함수가 실행 되는 위치에 아래 소스를 넣으시면 됩니다.

os.execl(sys.executable, sys.executable, *sys.argv)

예제)

import os
def mais():
...
if __name__ == "__main__":
main()
os.execl(sys.executable, sys.executable, *sys.argv)
view raw os.execl hosted with ❤ by GitHub

 

+ Recent posts