From ae3271bd1186534a1ed7a57354fd3d8167aa5728 Mon Sep 17 00:00:00 2001 From: dianavermilya Date: Thu, 30 Jul 2015 16:43:24 -0400 Subject: [PATCH] refactor api.py --- indicoio/utils/api.py | 41 ++++++++++++++++++++++------------------- 1 file changed, 22 insertions(+), 19 deletions(-) diff --git a/indicoio/utils/api.py b/indicoio/utils/api.py index 141cc0f..14c6555 100644 --- a/indicoio/utils/api.py +++ b/indicoio/utils/api.py @@ -9,36 +9,39 @@ from indicoio import JSON_HEADERS from indicoio import config def api_handler(arg, cloud, api, url_params=None, **kwargs): - if url_params is None: - url_params = {"api_key":None, batch:False } + """ + Sends finalized request data to ML server and receives response. + """ data = {'data': arg} data.update(**kwargs) json_data = json.dumps(data) - if not cloud: - cloud = config.cloud - - if cloud: - host = "%s.indico.domains" % cloud - - else: - # default to indico public cloud - host = config.PUBLIC_API_HOST - - url = config.url_protocol + "//%s/%s" % (host, api) - url = url + "/batch" if url_params.get("batch", False) else url - url += "?key=%s" % (url_params.get("api_key", None) or config.api_key) - apis = url_params.get("apis", []) - if apis: - url += "&apis=%s" % ",".join(apis) + cloud = cloud or config.cloud + host = "%s.indico.domains" % cloud if cloud else config.PUBLIC_API_HOST + url = create_url(host, api, url_params) response = requests.post(url, data=json_data, headers=JSON_HEADERS) + if response.status_code == 503 and cloud != None: raise IndicoError("Private cloud '%s' does not include api '%s'" % (cloud, api)) - + json_results = response.json() results = json_results.get('results', False) if results is False: error = json_results.get('error') raise IndicoError(error) return results + + +def create_url(host, api, url_params): + api_key = url_params.get("api_key") or config.api_key + is_batch = url_params.get("batch") + apis = url_params.get("apis") + + host_url_seg = config.url_protocol + "//%s" % host + api_url_seg = "/%s" % api + batch_url_seg = "/batch" if is_batch else "" + key_url_seg = "?key=%s" % api_key + multi_url_seg = "&apis=%s" % ",".join(apis) if apis else "" + + return host_url_seg + api_url_seg + batch_url_seg + key_url_seg + multi_url_seg