def make_request(self, method, uri, params=None, data=None, retries=0): if uri[-1] != '/': uri += '/' request_url = '{}/v2/{}'.format(self.auth.api_url, uri) if type(data) is dict or type(data) is list: data = json.dumps(data) headers = self._get_headers() try: if method in ('GET', 'DELETE'): if method == 'GET': headers.pop('Content-Type') response = self.session.request(method, request_url, params=params, headers=headers, verify=SSL_VERIFY) else: response = self.session.request(method, request_url, data=data, headers=headers, verify=SSL_VERIFY) logger.info('REQUEST: %s %s', method, request_url) except Exception: logger.exception('Error in request') raise exceptions.ApiError('Error in request') else: try: content = response.json() except json.JSONDecodeError: content = response.content status_code = response.status_code if logger.isEnabledFor(logging.DEBUG): logger.debug('RESPONSE: %s %s %s %s', method, request_url, content, status_code) else: logger.info('RESPONSE: %s %s %s', method, request_url, status_code) if status_code in (502, 503) and retries < self.retries: retries += 1 self.make_request(method, uri, params, data, retries) elif status_code == 500: retries_error = self.retries - 6 if retries < retries_error: logger.warning('Retry send %s %s %s %s', method, request_url, params, data) retries += 1 time.sleep(retries * 5) self.make_request(method, uri, params, data, retries) return self._parser_response(content, status_code)
def _parser_response(self, response): content = response.json() status_code = response.status_code if status_code == 200: return content elif status_code == 400: raise exceptions.ValidationError(content, status_code) elif status_code == 401: raise exceptions.Unauthorized(content, status_code) else: raise exceptions.ApiError(content, status_code)
def _make_request(self): try: url = '{}/v2/auth/'.format(self.api_url) data = {'username': self.username, 'password': self.password} response = requests.post(url, data=json.dumps(data), headers=self._get_headers()) except Exception: self.logger.exception('Error in request') raise exceptions.ApiError('Error in request') else: return self._parser_response(response)
def _parser_response(self, content, status_code): if status_code == 200: return content elif status_code == 400: raise exceptions.ValidationError(content, status_code) elif status_code == 401: raise exceptions.Unauthorized(content, status_code) elif status_code == 403: raise exceptions.Forbidden(content, status_code) elif status_code == 404: raise exceptions.NotFound(content, status_code) elif status_code == 409: raise exceptions.DocumentAlreadyExists(content, status_code) else: raise exceptions.ApiError(content, status_code)