Skip to content

Instantly share code, notes, and snippets.

@cortical-iv
Last active January 5, 2018 03:49
Show Gist options
  • Save cortical-iv/4c056a0c61a202fe5f955bfe773321e7 to your computer and use it in GitHub Desktop.
Save cortical-iv/4c056a0c61a202fe5f955bfe773321e7 to your computer and use it in GitHub Desktop.
Endpoint class example for Destiny 2 api
class Endpoint:
"""
Abstract end point class: this is never used directly. Concrete
endpoints inherit from this.
"""
def __init__(self, headers, request_parameters = None, url_arguments = None):
self.url_arguments = url_arguments
self.url_initial = self.make_url()
self.request_params = request_parameters
self.headers = headers
self.response = self.make_request()
self.request_duration = self.response.elapsed.total_seconds()
self.url = self.response.url
self.data = self.get_data()
def make_url(self):
"""Reimplement for each end point instance"""
return
def make_request(self):
try:
if self.request_params:
response = requests.get(self.url_initial, headers = self.headers, \
params = self.request_params)
else:
response = requests.get(self.url_initial, headers = self.headers)
if not response.ok:
response.raise_for_status()
except requests.exceptions.RequestException as requestExc:
msg = f"Endpoint.make_request() exception:\n{requestExc}"
logger.exception(msg)
raise
else:
return response
def get_data(self):
try:
response_json = self.response.json()
except json.JSONDecodeError as jsonError:
msg1 = f"JSONDecodeError in Endpoint.get_data()."
msg2 = "Response does not contain json-encoded data.\n"
msg3 = f"URL: {self.url}.\nError: '{jsonError}'"
msg = msg1 + msg2 + msg3
logger.exception(msg)
raise
try:
data = response_json['Response']
except KeyError as keyError:
error_code = response_json['ErrorCode']
error_status = response_json['ErrorStatus']
error_message = response_json['Message']
msg1 = f"KeyError in Endpoint.get_data().\nURL: {self.url}.\n"
msg2 = f"Error code {error_code}: {error_status}.\nMessage: {error_message}.\n"
msg = msg1 + msg2
logger.exception(msg)
raise
else:
return data
def __repr__(self):
return "Endpoint instance."
class GetProfile(Endpoint):
"""https://bungie-net.github.io/multi/operation_get_Destiny2-GetProfile.html"""
def __init__(self, headers, request_parameters = None, url_arguments = None):
super().__init__(headers, request_parameters, url_arguments)
def make_url(self):
url = f"{BASE_URL}{str(self.url_arguments['membership_type'])}/Profile/{self.url_arguments['member_id']}/"
return url
def __repr__(self):
return f"GetProfile instance.\nURL: {self.url}."
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment