|
| 1 | +from posixpath import join |
| 2 | +import threading |
| 3 | + |
| 4 | +from civis.response import PaginatedResponse, convert_response_data_type |
| 5 | + |
| 6 | + |
| 7 | +def tostr_urljoin(*x): |
| 8 | + return join(*map(str, x)) |
| 9 | + |
| 10 | + |
| 11 | +class CivisJobFailure(Exception): |
| 12 | + def __init__(self, err_msg, response=None): |
| 13 | + self.error_message = err_msg |
| 14 | + self.response = response |
| 15 | + |
| 16 | + def __str__(self): |
| 17 | + return self.error_message |
| 18 | + |
| 19 | + |
| 20 | +class CivisAPIError(Exception): |
| 21 | + def __init__(self, response): |
| 22 | + if response.content: # the API itself gave an error response |
| 23 | + json = response.json() |
| 24 | + self.error_message = json["errorDescription"] |
| 25 | + else: # this was something like a 502 |
| 26 | + self.error_message = response.reason |
| 27 | + |
| 28 | + self.status_code = response.status_code |
| 29 | + self._response = response |
| 30 | + |
| 31 | + def __str__(self): |
| 32 | + if self.status_code: |
| 33 | + return "({}) {}".format(self.status_code, self.error_message) |
| 34 | + else: |
| 35 | + return self.error_message |
| 36 | + |
| 37 | + |
| 38 | +class EmptyResultError(Exception): |
| 39 | + pass |
| 40 | + |
| 41 | + |
| 42 | +class CivisAPIKeyError(Exception): |
| 43 | + pass |
| 44 | + |
| 45 | + |
| 46 | +class Endpoint: |
| 47 | + |
| 48 | + _base_url = "https://api.civisanalytics.com/" |
| 49 | + _lock = threading.Lock() |
| 50 | + |
| 51 | + def __init__(self, session, return_type='civis'): |
| 52 | + self._session = session |
| 53 | + self._return_type = return_type |
| 54 | + |
| 55 | + def _build_path(self, path): |
| 56 | + if not path: |
| 57 | + return self._base_url |
| 58 | + return tostr_urljoin(self._base_url, path.strip("/")) |
| 59 | + |
| 60 | + def _make_request(self, method, path=None, params=None, data=None, |
| 61 | + **kwargs): |
| 62 | + url = self._build_path(path) |
| 63 | + |
| 64 | + with self._lock: |
| 65 | + response = self._session.request(method, url, json=data, |
| 66 | + params=params, **kwargs) |
| 67 | + |
| 68 | + if response.status_code in [204, 205]: |
| 69 | + return |
| 70 | + |
| 71 | + if response.status_code == 401: |
| 72 | + auth_error = response.headers["www-authenticate"] |
| 73 | + raise CivisAPIKeyError(auth_error) from CivisAPIError(response) |
| 74 | + |
| 75 | + if not response.ok: |
| 76 | + raise CivisAPIError(response) |
| 77 | + |
| 78 | + return response |
| 79 | + |
| 80 | + def _call_api(self, method, path=None, params=None, data=None, **kwargs): |
| 81 | + iterator = kwargs.pop('iterator', False) |
| 82 | + |
| 83 | + if iterator: |
| 84 | + return PaginatedResponse(path, params, self) |
| 85 | + else: |
| 86 | + resp = self._make_request(method, path, params, data, **kwargs) |
| 87 | + resp = convert_response_data_type(resp, |
| 88 | + return_type=self._return_type) |
| 89 | + return resp |
0 commit comments