Ejemplo n.º 1
0
	def _request(self, route, method, parameters=None):
		"""Make an HTTP request."""
		params = {}
		if parameters:
			params = parameters.copy()

		# Micro cache?
		if self.micro_cache is False:
			params["no_micro_cache"] = 1

		# Is there a token?.
		if self.access_token:
			params["access_token"] = self.access_token

		# override instance's API key if one is supplied in the params
		if "api_key" not in params or not params.get("api_key"):
			params["api_key"] = self.api_key

		uri = self._routes[route]

		# 'RESTful' URLs.
		if "{" in uri:
			for k in params:
				uri = uri.replace("{" + k + "}", str(params[k]))

		url = self._root + uri

		if self.debug:
			logger.debug(" Request: {method} {url} {params}".format(
				method=method,
				url=url,
				params=params))

		try:
			r = self.reqsession.request(method,
					url,
					data=params if method in ["POST", "PUT"] else None,
					params=params if method in ["GET", "DELETE"] else None,
					verify=False,
					allow_redirects=True,
					timeout=self._timeout,
					proxies=self.proxies)
		except requests.ConnectionError:
			raise ex.ClientNetworkException("Gateway connection error", code=503)
		except requests.Timeout:
			raise ex.ClientNetworkException("Gateway timed out", code=504)
		except requests.HTTPError:
			raise ex.ClientNetworkException("Invalid response from gateway", code=502)
		except Exception as e:
			raise ex.ClientNetworkException(e.message, code=500)

		if self.debug:
			logger.debug(" Response: {code} {content}".format(
				code=r.status_code,
				content=r.content))

		# Validate the content type.
		if "json" in r.headers["content-type"]:
			try:
				data = json.loads(r.content.decode('utf8'))
			except:
				raise ex.DataException("Couldn't parse JSON response")

			# api error
			if data["status"] == "error":
				if r.status_code == 403:
					if self.session_hook:
						self.session_hook()
						return

				# native Kite errors
				exp = getattr(ex, data["error_type"])
				if data["error_type"] == "TwoFAException":
					raise(ex.TwoFAException(data["message"],
											questions=data["questions"] if "questions" in data else [],
											code=r.status_code))
				elif exp:
					raise(exp(data["message"], code=r.status_code))
				else:
					raise(ex.GeneralException(data["message"], code=r.status_code))

			return data["data"]
		elif "csv" in r.headers["content-type"]:
			return r.content
		else:
			raise ex.DataException("Unknown Content-Type (%s) in response: (%s)" % (r.headers["content-type"], r.content))
Ejemplo n.º 2
0
    def _request(self, route, method, parameters=None):
        """Make an HTTP request."""
        params = parameters.copy() if parameters else {}

        # Form a restful URL
        uri = self._routes[route].format(**params)
        url = urljoin(self.root, '/oms' + uri)

        # Custom headers
        headers = self.oms_headers()

        if self.debug:
            log.debug("Request: {method} {url} {params} {headers}".format(
                method=method, url=url, params=params, headers=headers))

        try:
            r = self.reqsession.request(
                method,
                url,
                data=params if method in ["POST", "PUT"] else None,
                params=params if method in ["GET", "DELETE"] else None,
                headers=headers,
                verify=not self.disable_ssl,
                allow_redirects=True,
                timeout=self.timeout,
                proxies=self.proxies)
            self.r = r
        # Any requests lib related exceptions are raised here - http://docs.python-requests.org/en/master/_modules/requests/exceptions/
        except Exception as e:
            raise e

        if self.debug:
            log.debug("Response: {code} {content}".format(code=r.status_code,
                                                          content=r.content))

        # Validate the content type.
        if "json" in r.headers["content-type"]:
            try:
                data = json.loads(r.content.decode("utf8"))
            except ValueError:
                raise ex.DataException(
                    "Couldn't parse the JSON response received from the server: {content}"
                    .format(content=r.content))

            # api error
            if data.get("error_type"):
                # Call session hook if its registered and TokenException is raised
                if self.session_expiry_hook and r.status_code == 403 and data[
                        "error_type"] == "TokenException":
                    self.session_expiry_hook()

                # native Kite errors
                exp = getattr(ex, data["error_type"], ex.GeneralException)
                raise exp(data["message"], code=r.status_code)

            return data["data"]
        elif "csv" in r.headers["content-type"]:
            return r.content
        else:
            raise ex.DataException(
                "Unknown Content-Type ({content_type}) with response: ({content})"
                .format(content_type=r.headers["content-type"],
                        content=r.content))
Ejemplo n.º 3
0
    def _request(self,
                 route,
                 method,
                 url_args=None,
                 params=None,
                 is_json=False):
        '''Make an HTTP request.'''
        # Form a restful URL
        if url_args:
            uri = self._routes[route].format(**url_args)
        else:
            uri = self._routes[route]

        url = urljoin(self.root, uri)

        headers = self.headers

        # Custom headers
        # headers = {
        #     'X-Kite-Version': '3',  # For version 3
        #     'User-Agent': self._user_agent()
        # }

        # if self.api_key and self.access_token:
        #     # set authorization header
        #     auth_header = self.api_key + ':' + self.access_token
        #     headers['Authorization'] = 'token {}'.format(auth_header)

        if self.debug:
            log.debug('Request: {method} {url} {params} {headers}'.format(
                method=method, url=url, params=params, headers=headers))

        try:
            r = self.reqsession.request(
                method,
                url,
                json=params if
                (method in ['POST', 'PUT'] and is_json) else None,
                data=params if
                (method in ['POST', 'PUT'] and not is_json) else None,
                params=params if method in ['GET', 'DELETE'] else None,
                headers=headers,
                verify=not self.disable_ssl,
                allow_redirects=True,
                timeout=self.timeout,
                proxies=self.proxies)
        # Any requests lib related exceptions are raised here - http://docs.python-requests.org/en/master/_modules/requests/exceptions/
        except Exception as e:
            raise e

        if self.debug:
            log.debug('Response: {code} {content}'.format(code=r.status_code,
                                                          content=r.content))

        # Validate the content type.
        if 'json' in r.headers['content-type']:
            try:
                data = json.loads(r.content.decode('utf8'))
            except ValueError:
                raise ex.DataException(
                    'Could not parse the JSON response received from the server: {content}'
                    .format(content=r.content))

            # api error
            if data.get('error_type'):
                # Call session hook if its registered and TokenException is raised
                if self.session_expiry_hook and r.status_code == 403 and data[
                        'error_type'] == 'TokenException':
                    self.session_expiry_hook()

                # native Kite errors
                exp = getattr(ex, data['error_type'], ex.GeneralException)
                raise exp(data['message'], code=r.status_code)

            return data['data']
        elif 'csv' in r.headers['content-type']:
            return r.content
        else:
            raise ex.DataException(
                'Unknown Content-Type ({content_type}) with response: ({content})'
                .format(content_type=r.headers['content-type'],
                        content=r.content))
Ejemplo n.º 4
0
    def _request(self,
                 route,
                 method,
                 url_args=None,
                 params=None,
                 is_json=False,
                 query_params=None):
        """Make an HTTP request."""
        # Form a restful URL
        if url_args:
            uri = self._routes[route].format(**url_args)
        else:
            uri = self._routes[route]

        url = urljoin(self.root, uri)

        # Custom headers
        headers = {
            "X-Kite-Version": "3",  # For version 3
            "User-Agent": self._user_agent()
        }

        if self.api_key and self.access_token:
            # set authorization header
            auth_header = self.api_key + ":" + self.access_token
            headers["Authorization"] = "token {}".format(auth_header)

        if self.debug:
            log.debug("Request: {method} {url} {params} {headers}".format(
                method=method, url=url, params=params, headers=headers))

        # prepare url query params
        if method in ["GET", "DELETE"]:
            query_params = params

        try:
            r = self.reqsession.request(
                method,
                url,
                json=params if
                (method in ["POST", "PUT"] and is_json) else None,
                data=params if
                (method in ["POST", "PUT"] and not is_json) else None,
                params=query_params,
                headers=headers,
                verify=not self.disable_ssl,
                allow_redirects=True,
                timeout=self.timeout,
                proxies=self.proxies)
        # Any requests lib related exceptions are raised here - http://docs.python-requests.org/en/master/_modules/requests/exceptions/
        except Exception as e:
            raise e

        if self.debug:
            log.debug("Response: {code} {content}".format(code=r.status_code,
                                                          content=r.content))

        # Validate the content type.
        if "json" in r.headers["content-type"]:
            try:
                data = json.loads(r.content.decode("utf8"))
            except ValueError:
                raise ex.DataException(
                    "Couldn't parse the JSON response received from the server: {content}"
                    .format(content=r.content))

            # api error
            if data.get("status") == "error" or data.get("error_type"):
                # Call session hook if its registered and TokenException is raised
                if self.session_expiry_hook and r.status_code == 403 and data[
                        "error_type"] == "TokenException":
                    self.session_expiry_hook()

                # native Kite errors
                exp = getattr(ex, data.get("error_type"), ex.GeneralException)
                raise exp(data["message"], code=r.status_code)

            return data["data"]
        elif "csv" in r.headers["content-type"]:
            return r.content
        else:
            raise ex.DataException(
                "Unknown Content-Type ({content_type}) with response: ({content})"
                .format(content_type=r.headers["content-type"],
                        content=r.content))
Ejemplo n.º 5
0
    def _request(self,
                 route,
                 method,
                 url_args=None,
                 params=None,
                 is_json=False,
                 query_params=None):
        if url_args:
            uri = self._routes[route].format(**url_args)
        else:
            uri = self._routes[route]

        url = urljoin(self.root, self.url_patch + uri)

        # prepare url query params
        if method in ["GET", "DELETE"]:
            query_params = params

        # Custom headers
        headers = self.custom_headers()

        if self.debug:
            log.debug("Request: {method} {url} {params} {headers}".format(
                method=method, url=url, params=params, headers=headers))

        try:
            r = self.reqsession.request(
                method,
                url,
                json=params if
                (method in ["POST", "PUT"] and is_json) else None,
                data=params if method in ["POST", "PUT"] else None,
                params=query_params if method in ["GET", "DELETE"] else None,
                headers=headers,
                verify=not self.disable_ssl,
                allow_redirects=True,
                timeout=self.timeout,
                proxies=self.proxies)
            self.r = r
        except Exception as e:
            raise e

        if self.debug:
            log.debug("Response: {code} {content}".format(code=r.status_code,
                                                          content=r.content))

        # Validate the content type.
        if "json" in r.headers["content-type"]:
            try:
                data = json.loads(r.content.decode("utf8"))
            except ValueError:
                raise ex.DataException(
                    "Couldn't parse the JSON response received from the server: {content}"
                    .format(content=r.content))

            # api error
            if data.get("error_type"):
                # Call session hook if its registered and TokenException is raised
                if self.session_expiry_hook and r.status_code == 403 and data[
                        "error_type"] == "TokenException":
                    self.session_expiry_hook()

                # native Kite errors
                exp = getattr(ex, data["error_type"], ex.GeneralException)
                raise exp(data["message"], code=r.status_code)

            return data["data"]
        elif "csv" in r.headers["content-type"]:
            return r.content
        else:
            raise ex.DataException(
                "Unknown Content-Type ({content_type}) with response: ({content})"
                .format(content_type=r.headers["content-type"],
                        content=r.content))