def make_request(self, method, uri, data=None, retries=0): 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 == 'GET': response = self.session.request( method, request_url, headers=headers ) else: response = self.session.request( method, request_url, data=data, headers=headers ) self.logger.info('REQUEST: %s %s' % (method, request_url)) except Exception: self.logger.exception('Error in request') raise exceptions.ApiError('Error in request') else: try: content = response.json() except json.JSONDecodeError: content = response.text status_code = response.status_code try: return self._parser_response(content, status_code) except exceptions.Unauthorized as err: if retries < self.retries: time.sleep(5 + (retries * 5)) self.auth.generate_token() return self.make_request( method=method, uri=uri, data=data, retries=retries + 1) self.logger.error('Unauthorized %s %s.', content, status_code) raise exceptions.Unauthorized(err.message, err.status_code) except exceptions.ApiError as err: if retries < self.retries: return self.make_request( method=method, uri=uri, data=data, retries=retries + 1) self.logger.error('ApiError %s %s.', content, status_code) raise exceptions.ApiError(err.message, err.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 = self.session.request('POST', url, data=json.dumps(data), headers=self._get_headers(), verify=SSL_VERIFY) 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 in (200, 202): self.logger.debug('Success %s %s.', content, status_code) return content elif status_code == 400: self.logger.error('ValidationError %s %s.', content, status_code) raise exceptions.ValidationError(content, status_code) elif status_code == 401: self.logger.warning('Unauthorized %s %s.', content, status_code) raise exceptions.Unauthorized(content, status_code) elif status_code == 403: self.logger.error('Forbidden %s %s.', content, status_code) raise exceptions.Forbidden(content, status_code) elif status_code == 404: self.logger.error('NotFound %s %s.', content, status_code) raise exceptions.NotFound(content, status_code) else: self.logger.warning('ApiError %s %s.', content, status_code) raise exceptions.ApiError(content, status_code)