Update api.py

This commit is contained in:
Richard Bronkhorst 2023-06-12 12:23:08 +02:00
parent 849964b659
commit b19a52d1aa

View File

@ -4,12 +4,15 @@ from nullptr.models.waypoint import Waypoint
from nullptr.models.marketplace import Marketplace from nullptr.models.marketplace import Marketplace
from nullptr.models.jumpgate import Jumpgate from nullptr.models.jumpgate import Jumpgate
from .util import * from .util import *
from time import sleep
class ApiError(Exception): class ApiError(Exception):
def __init__(self, msg, code): def __init__(self, msg, code):
super().__init__(msg) super().__init__(msg)
self.code = code self.code = code
class ApiLimitError(Exception):
pass
class Api: class Api:
def __init__(self, store, agent): def __init__(self, store, agent):
self.agent = agent self.agent = agent
@ -23,13 +26,22 @@ class Api:
return self.agent.token return self.agent.token
def request(self, method, path, data=None, need_token=True, params={}): def request(self, method, path, data=None, need_token=True, params={}):
try:
return self.request_once(method, path, data, need_token, params)
except ApiLimitError:
print('oops, hit the limit. take a break')
sleep(10)
return self.request_once(method, path, data, need_token, params)
def request_once(self, method, path, data=None, need_token=True, params={}):
headers = {} headers = {}
if need_token: if need_token:
headers['Authorization'] = 'Bearer ' + self.token() headers['Authorization'] = 'Bearer ' + self.token()
if method == 'get': if method == 'get':
params['limit'] = 20 params['limit'] = 20
r = requests.request(method, self.root+path, json=data, headers=headers, params=params) r = requests.request(method, self.root+path, json=data, headers=headers, params=params)
if r.status_code == 429:
raise ApiLimitError()
result = r.json() result = r.json()
self.last_result = result self.last_result = result
if result is None: if result is None: