def from_json(json_object): """ Creates a object from json-dict/ json-string @param json_object json.dict/ json-string @return client client object """ client = None try: if type(json_object) == str: json_object = json.loads(json_object) json_object_keys = list(json_object.keys()) client = FileManager(host=json_object['host']) if "user_token" in json_object_keys: client.user_token = json_object['user_token'] if "protocol" in json_object_keys: client.protocol = json_object['protocol'] if "proxies" in json_object_keys: client.proxies = json_object['proxies'] if "timeout" in json_object_keys: client.timeout = json_object['timeout'] if "avoid_ssl_certificate" in json_object_keys: client.avoid_ssl_certificate = json_object[ 'avoid_ssl_certificate'] if "raise_exceptions" in json_object_keys: client.raise_exceptions = json_object['raise_exceptions'] log.info("Imported json {}".format(json_object)) except Exception as e: log.error("Not possible to import object from json: {}".format(e)) return client
def __init__(self, host, port=None, iot_client=config.IOT_CLIENT, iot_client_token=config.IOT_CLIENT_TOKEN): """ Class IotBrokerClient to connect with Iot-Broker of OnesaitPlatform @param host Onesaitplatform host @param iot_client Onesaitplatform Iot-Client @param iot_client_token Onesaitplatform iot-Client-Token """ #super().__init__(host, port=port) # only python > 3 Client.__init__(self, host, port=port) # python > 2.7 & <= 3.7.1 self.iot_client = iot_client self.iot_clientId = iot_client + ":PythonClient" self.iot_client_token = iot_client_token self.session_key = None log.info("Created client with iot-broker \ host:{}, path:{}, client:{}, token:{}".format( host, self.__iot_broker_path, iot_client, iot_client_token)) self.add_to_debug_trace("Created client with \ iot-broker host:{}, path:{}, \ client:{}, token:{}".format( host, self.__iot_broker_path, iot_client, iot_client_token))
def __init__(self, host, port=None, username=None, password=None, vertical="onesaitplatform"): """ Class AuthClient to login and refresh token of OnesaitPlatform @param host Onesaitplatform host @param port Onesaitplatform port @param username Onesaitplatform username @param password Onesaitplatform password @param vertical Onesaitplatform vertical (default=''onesaitplatform') """ Client.__init__(self, host, port=port) self.username = username self.password = password self.vertical = vertical self.token = None log.info("Created client with controlpanel-auth \ host:{}, path:{}, username:{}, vertical:{}".format( host, self.__control_panel_path, username, vertical)) self.add_to_debug_trace("Created client with controlpanel-auth \ host:{}, path:{}, username:{}, vertical:{}".format( host, self.__control_panel_path, username, vertical))
def to_json(self, as_string=False): """ Export object to json @param as_string If json dumped (String) @return json_obj json-dict/ json string """ json_obj = dict() json_obj["host"] = self.host json_obj["port"] = self.port json_obj["protocol"] = self.protocol json_obj["username"] = self.username json_obj["password"] = self.password json_obj["vertical"] = self.vertical json_obj["token"] = self.token.to_json() json_obj["proxies"] = self.proxies json_obj["timeout"] = self.timeout json_obj["avoid_ssl_certificate"] = self.avoid_ssl_certificate json_obj["raise_exceptions"] = self.raise_exceptions if as_string: json_obj = json.dumps(json_obj) log.info("Exported json {}".format(json_obj)) self.add_to_debug_trace("Exported json {}".format(json_obj)) return json_obj
def to_json(self, as_string=False): """ Export object to json @param as_string If json dumped (String) @return json_obj json-dict/ json string """ json_obj = dict() json_obj["host"] = self.host json_obj["port"] = self.port json_obj["protocol"] = self.protocol json_obj["is_connected"] = self.is_connected json_obj["proxies"] = self.proxies json_obj["timeout"] = self.timeout json_obj["avoid_ssl_certificate"] = self.avoid_ssl_certificate json_obj["raise_exceptions"] = self.raise_exceptions json_obj["model_endpoint"] = self.model_endpoint json_obj["model_version"] = self.model_version json_obj["token"] = self.token if as_string: json_obj = json.dumps(json_obj) log.info("Exported json {}".format(json_obj)) self.add_to_debug_trace("Exported json {}".format(json_obj)) return json_obj
def call(self, method, url, headers=None, params=None, body=None): """ Make an HTTP request @param metod HTTP method ['GET', 'PUT', ...] @param url url path to append to host @param header request headers @param params request params @param body request body @return requests.request(...) """ method = method.upper() log.info("Calling rest api, method:{}, url:{}, headers:{}, params:{}". format(method, url, headers, params)) self.add_to_debug_trace( "Calling rest api, method:{}, url:{}, headers:{}, params:{}". format(method, url, headers, params)) response = requests.request(method, url, headers=headers, params=params, json=body, verify=not self.avoid_ssl_certificate, timeout=self.timeout, proxies=self.proxies) log.info("Call rest api response: {}".format(response)) self.add_to_debug_trace("Call rest api response: {}".format(response)) return response
def __init__(self, host, port=None): """ Class ApiManagerClient to connect with Api-Manager and APIs of OnesaitPlatform @param host Onesaitplatform host """ #super().__init__(host, port=port) # only python > 3 Client.__init__(self, host, port=port) # python > 2.7 & <= 3.7.1 self.token = None log.info("Connection Params: " + self.host + "/(" + self.api_manager_path + " - " + self.api_caller_path + ")") self.add_to_debug_trace("Connection Params: " + self.host + "/(" + self.api_manager_path + " - " + self.api_caller_path + ")")
def load_proxies_automatically(self): proxies = {} if "http_proxy" in os.environ.keys(): proxies["http"] = os.environ["http_proxy"] elif "HTTP_PROXY" in os.environ.keys(): proxies["http"] = os.environ["HTTP_PROXY"] if "https_proxy" in os.environ.keys(): proxies["https"] = os.environ["https_proxy"] elif "HTTPS_PROXY" in os.environ.keys(): proxies["https"] = os.environ["HTTPS_PROXY"] if proxies != {}: log.info("Detected proxies: {}".format(proxies)) self.__proxies = proxies
def update(self, ontology, query=None, query_type="NATIVE", data=None, where=None, return_ids=True): """ Make a update to iot-broker service of the platform @param ontology ontology name @param query query expression @param query_type quert type ['NATIVE'] @param data data to update @param where selection criteria for the update @param return_ids return ids in response (optional, default: True) @return ok, info """ _ok = False _res = None try: response = self.raw_update(ontology, query, query_type, data, where, return_ids) if self.is_correct_status_code(response.status_code): _res = response.json() log.info("Query result: {}".format(response.text)) self.add_to_debug_trace("Query result: {}".format( response.text)) _ok = True else: log.info("Bad response: {} - {}".format( response.status_code, response.text)) self.add_to_debug_trace("Bad response: {} - {}".format( response.status_code, response.text)) _res = response.text except Exception as e: log.error("Not possible to update with iot-broker: {}".format(e)) self.add_to_debug_trace( "Not possible to update with iot-broker: {}".format(e)) self.raise_exception_if_enabled(e) _res = e return _ok, _res
def to_json(self, as_string=False): """ Export object to json @param as_string If json dumped (String) @return json_obj json-dict/ json string """ self.debug_trace = [] json_obj = dict(self.__dict__) json_obj.pop("debug_trace", None) if as_string: json_obj = json.dumps(json_obj) log.info("Exported json {}".format(json_obj)) self.add_to_debug_trace("Exported json {}".format(json_obj)) return json_obj
def from_json(json_object): """ Creates a object from json-dict/ json-string @param json_object json.dict/ json-string @return client client object """ client = None try: if type(json_object) == str: json_object = json.loads(json_object) json_object_keys = list(json_object.keys()) client = Client(host=json_object['host']) if "port" in json_object_keys: client.port = json_object['port'] if "protocol" in json_object_keys: client.protocol = json_object['protocol'] if "is_connected" in json_object_keys: client.is_connected = json_object['is_connected'] if "proxies" in json_object_keys: client.proxies = json_object['proxies'] if "timeout" in json_object_keys: client.timeout = json_object['timeout'] if "avoid_ssl_certificate" in json_object_keys: client.avoid_ssl_certificate = json_object[ 'avoid_ssl_certificate'] if "raise_exceptions" in json_object_keys: client.raise_exceptions = json_object['raise_exceptions'] if "model_endpoint" in json_object_keys: client.model_endpoint = json_object['model_endpoint'] if "model_version" in json_object_keys: client.model_version = json_object['model_version'] if "token" in json_object_keys: client.token = json_object['token'] log.info("Imported json {}".format(json_object)) client.add_to_debug_trace("Imported json {}".format(json_object)) except Exception as e: log.error("Not possible to import object from json: {}".format(e)) return client
def from_json(json_object): """ Creates a object from json-dict/ json-string @param json_object json.dict/ json-string @return client client object """ client = None try: if type(json_object) == str: json_object = json.loads(json_object) json_object_keys = list(json_object.keys()) client = AuthClient(host=json_object['host']) if "port" in json_object_keys: client.port = json_object['port'] if "username" in json_object_keys: client.username = json_object['username'] if "password" in json_object_keys: client.password = json_object['password'] if "vertical" in json_object_keys: client.vertical = json_object['vertical'] if "token" in json_object_keys: client.token = Token.from_json(json_object['token']) if "protocol" in json_object_keys: client.protocol = json_object['protocol'] if "proxies" in json_object_keys: client.proxies = json_object['proxies'] if "timeout" in json_object_keys: client.timeout = json_object['timeout'] if "avoid_ssl_certificate" in json_object_keys: client.avoid_ssl_certificate = json_object[ 'avoid_ssl_certificate'] if "raise_exceptions" in json_object_keys: client.raise_exceptions = json_object['raise_exceptions'] log.info("Imported json {}".format(json_object)) client.add_to_debug_trace("Imported json {}".format(json_object)) except Exception as e: log.error("Not possible to import object from json: {}".format(e)) return client
def restart(self): """ Restar conection: - leave() - join() @return ok, info """ log.info( "Restarting connection with session_key:{}, connected:{}".format( self.session_key, self.is_connected)) _ok_leave, _res_leave = self.leave() _ok_join, _res_join = self.join() if not _ok_join: log.warning("Not possible to restart connexion with iot-broker") self.add_to_debug_trace( "Not possible to restart connexion with iot-broker") return _ok_join, _res_join
def query_batch(self, ontology, query, query_type, batch_size=None): """ Make a query to iot-broker service of the platform paginated by batch size @param ontology ontology name @param query query expression @param query_type quert type ['NATIVE', 'SQL'] @param batch_size batch size (default from configuration) @return ok, info """ log.info("Making query batch to ontology:{}, query:{}, query_type:{}". format(ontology, query, query_type)) _ok = False _res = None if batch_size is None: batch_size = self.batch_size offset = 0 limit = batch_size res_query_count = batch_size _res = [] while res_query_count == batch_size: res_query_count = 0 step_query = self._query_batch_str(query, offset, limit, query_type) ok_query, res_query = self.query(ontology, step_query, query_type) if ok_query: res_query_count = len(res_query) _res += res_query offset += batch_size _ok = ok_query return _ok, _res
def raw_leave(self): """ Logout in the platform with session token @return response """ log.info("Leaving connection with session_key:{}".format( self.session_key)) if self.is_connected: url = self.__leave_template.substitute(protocol=self.protocol, host=self.hostport, path=self.__iot_broker_path) headers = {RestHeaders.AUTHORIZATION.value: self.session_key} response = self.call(RestMethods.GET.value, url, headers=headers) self.is_connected = False self.session_key = None log.info("Disconnected correctly: {}".format(response.text)) self.add_to_debug_trace("Disconnected correctly: {}".format( response.text)) else: log.info("There is not connection, please join() before leave()") self.add_to_debug_trace( "There is not connection, please join() before leave()") return response
def from_json(json_object): """ Creates a object from json-dict/ json-string @param json_object json.dict/ json-string @return connection connection object """ connection = None try: if type(json_object) == str: json_object = json.loads(json_object) connection = ApiManagerClient(host=json_object['host']) connection.is_connected = json_object['is_connected'] log.info("Imported json {}".format(json_object)) connection.add_to_debug_trace( "Imported json {}".format(json_object)) except Exception as e: log.error("Not possible to import object from json: {}".format(e)) return connection
def query(self, ontology, query, query_type): """ Make a query to iot-broker service of the platform @param ontology ontology name @param query query expression @param query_type quert type ['NATIVE', 'SQL'] @return ok, info """ _ok = False _res = None try: response = self.raw_query(ontology, query, query_type) if self.is_correct_status_code(response.status_code): _res = response.json() log.info("Response: {} - {}".format( response.status_code, _res[0] if len(_res) > 0 else [])) self.add_to_debug_trace("Response: {} - {}".format( response.status_code, _res[0] if len(_res) > 0 else [])) _ok = True else: log.info("Bad response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) self.add_to_debug_trace( "Bad response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) _res = response.text except Exception as e: log.error("Not possible to query iot-broker: {}".format(e)) self.add_to_debug_trace( "Not possible to query iot-broker: {}".format(e)) self.raise_exception_if_enabled(e) _res = e return _ok, _res
def request(self, method, url=None, name=None, version=None, path_params=None, query_params=None, body=None): """ Make a request to an API rest @param method method (hhtp method) @param url url with path params and query params @param name API rest name * @param version API rest version * @param path_params path_params * @param query_params query_params * @param body body * If url != None: api_path = generate_url_request(name, version, path_params, query_params) * else: api_path = url @return ok, info """ _ok = False _res = None try: log.info("Making request: url:{}".format(url)) self.raise_exception_if_not_token() if isinstance(version, int) or isinstance(version, float): version = str(int(version)) if url is None: api_path = self.generate_url_request(name=name, version=version, path_params=path_params, query_params=query_params) else: api_path = url url = self.__request_template.substitute(protocol=self.protocol, host=self.hostport, path=self.api_caller_path, api_path=api_path ) headers = self.__headers response = self.call(method, url, headers=headers, body=body) log.info("Response: {} - {}".format(response.status_code, response.text)) self.add_to_debug_trace("Response: {} - {}".format(response.status_code, response.text)) if response.status_code == 200: _res = response.json() log.info("Query result: {}".format(response.text)) self.add_to_debug_trace("Query result: {}".format(response.text)) _ok = True else: raise Exception("Response: {} - {}".format(response.status_code, response.text)) except Exception as e: log.error("Not possible to query api-manager: {}".format(e)) self.add_to_debug_trace("Not possible to query api-manager: {}".format(e)) _res = e return _ok, _res
def delete(self, ontology, entity_id, return_ids=True): """ Make a insert to iot-broker service of the platform @param ontology ontology name @param entity_id entity object id @param return_ids return ids in response (optional, default: True) @return ok, info """ _ok = False _res = None try: response = self.raw_delete(ontology, entity_id, return_ids) if self.is_correct_status_code(response.status_code): _res = response.json() log.info("Query result: {}".format(response.text)) self.add_to_debug_trace("Query result: {}".format( response.text)) _ok = True else: log.info("Bad response: {} - {}".format( response.status_code, response.text)) self.add_to_debug_trace("Bad response: {} - {}".format( response.status_code, response.text)) _res = response.text except Exception as e: log.error("Not possible to delete with iot-broker: {}".format(e)) self.add_to_debug_trace( "Not possible to delete with iot-broker: {}".format(e)) self.raise_exception_if_enabled(e) _res = e return _ok, _res
def insert(self, ontology, list_data): """ Make a insert to iot-broker service of the platform @param ontology ontology name @param list_data list with data to insert @return ok, info """ _ok = False _res = None try: response = self.raw_insert(ontology, list_data) if self.is_correct_status_code(response.status_code): _res = response.json() log.info("Query result: {}".format(response.text)) self.add_to_debug_trace("Query result: {}".format( response.text)) _ok = True else: log.info("Bad response: {} - {}".format( response.status_code, response.text)) self.add_to_debug_trace("Bad response: {} - {}".format( response.status_code, response.text)) _res = response.text except Exception as e: log.error("Not possible to insert with iot-broker: {}".format(e)) self.add_to_debug_trace( "Not possible to insert with iot-broker: {}".format(e)) self.raise_exception_if_enabled(e) _res = e return _ok, _res
def delete(self, identification, version): """ Delete an API rest @param identification API identification (name) @param version API version @return ok, info """ _ok = False _res = None try: log.info("Making delete") if isinstance(version, str): version = version.replace("v", "") # case vX -> X self.raise_exception_if_not_token() url = self.__delete_template.substitute( protocol=self.protocol, host=self.hostport, path=self.api_manager_path, identification=identification, version=version) headers = self.__headers response = self.call(RestMethods.DELETE.value, url, headers=headers) log.info("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) self.add_to_debug_trace("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) if response.status_code == 200: _res = response.json() log.info("Query result: {text}".format(text=response.text)) self.add_to_debug_trace( "Query result: {text}".format(text=response.text)) _ok = True else: raise Exception("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) except Exception as e: log.error("Not possible to query api-manager: {exception}".format( exception=e)) self.add_to_debug_trace( "Not possible to query api-manager: {exception}".format( exception=e)) _res = e return _ok, _res
def find(self, identification, state, user): """ Find API rest information @param identification API identification (name) @param state API state @param user API creation user @return ok, info """ _ok = False _res = None try: log.info( "Making find: identification:{}, state:{}, user:{}".format( identification, state, user)) self.raise_exception_if_not_token() url = self.__find_template.substitute( protocol=self.protocol, host=self.hostport, path=self.api_manager_path, identification=identification, state=state, user=user) headers = self.__headers response = self.call(RestMethods.GET.value, url, headers=headers) log.info("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) self.add_to_debug_trace("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) if response.status_code == 200: _res = response.json() log.info("Query result: {text}".format(text=response.text)) self.add_to_debug_trace( "Query result: {text}".format(text=response.text)) _ok = True else: raise Exception("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) except Exception as e: log.error("Not possible to query api-manager: {exception}".format( exception=e)) self.add_to_debug_trace( "Not possible to query api-manager: {exception}".format( exception=e)) _res = e return _ok, _res
def create(self, json_obj): """ Create an API rest from json object @param json_obj json object of the API @return ok, info """ _ok = False _res = None try: log.info("Making create") if isinstance(json_obj, str): json_obj = json.loads(json_obj) self.raise_exception_if_not_token() url = self.__create_template.substitute(protocol=self.protocol, host=self.hostport, path=self.api_manager_path) headers = self.__headers response = self.call(RestMethods.POST.value, url, headers=headers, body=json_obj) log.info("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) self.add_to_debug_trace("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) if response.status_code == 200: _res = response.json() log.info("Query result: {text}".format(text=response.text)) self.add_to_debug_trace( "Query result: {text}".format(text=response.text)) _ok = True else: raise Exception("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) except Exception as e: log.error("Not possible to query api-manager: {exception}".format( exception=e)) self.add_to_debug_trace( "Not possible to query api-manager: {exception}".format( exception=e)) _res = e return _ok, _res
def raw_query(self, ontology, query, query_type): """ Make a query to iot-broker service of the platform @param ontology ontology name @param query query expression @param query_type quert type ['NATIVE', 'SQL'] @return response """ assert ontology != None, "Invalid input ontology" assert query != None, "Invalid input query" assert query_type != None, "Invalid input query_type" log.info("Making query to ontology:{}, query:{}, query_type:{}".format( ontology, query, query_type)) url = self.__query_template.substitute(protocol=self.protocol, host=self.hostport, path=self.__iot_broker_path, ontology=ontology) querystring = {"query": query, "queryType": query_type.upper()} headers = {RestHeaders.AUTHORIZATION.value: self.session_key} response = self.call(RestMethods.GET.value, url, headers=headers, params=querystring) if response.status_code != 200: log.warn("Response: {} - {}".format(response.status_code, response.text)) self.add_to_debug_trace("Response: {} - {}".format( response.status_code, response.text)) log.info( "Not possible to connect ({}) - {}, reconnecting...".format( response.status_code, response.text)) _ok_reconnect, _res_reconnect = self.restart() log.info("Reconnected: {} - {}".format(_ok_reconnect, _res_reconnect)) self.add_to_debug_trace("Reconnected: {} - {}".format( _ok_reconnect, _res_reconnect)) if _ok_reconnect: headers = {RestHeaders.AUTHORIZATION.value: self.session_key} response = self.call(RestMethods.GET.value, url, headers=headers, params=querystring) return response
def raw_refresh(self, refresh_token=None): """ Login in the platform with User credentials @return response """ if not isinstance(self.token, Token): raise ValueError( "Token must be a valid Token instance, use login before") if isinstance(refresh_token, str): if refresh_token.lower().startswith("bearer "): self.token.refresh_token = refresh_token.split("bearer ")[-1] else: self.token.refresh_token = refresh_token log.info( "Refreshing token with controlpanel-auth host:{}, path:{}, refresh_token:{}" .format(self.host, self.__control_panel_path, self.token.refresh_token)) url = self.__refresh_template.substitute( protocol=self.protocol, host=self.hostport, path=self.__control_panel_path) body = self.token.refresh_token headers = { RestHeaders.ACCEPT_STR.value: RestHeaders.ACCEPT_ALL.value, RestHeaders.CONT_TYPE.value: RestHeaders.APP_JSON.value } response = self.call(RestMethods.POST.value, url, headers, data=body) if response.status_code == 200 and len(response.content): self.token = Token.from_json(response.json()) log.info("Refresh correctly, access token: {}".format(self.token)) self.add_to_debug_trace( "Refresh correctly, access token: {}".format(self.token)) else: log.info("Not possible to Refresh: {} - {}".format( response.status_code, response.text)) self.add_to_debug_trace("Not possible to Refresh: {} - {}".format( response.status_code, response.text)) return response
def raw_join(self, iot_client=None, iot_client_token=None): """ Login in the platform with Iot-Client credentials @return response """ if iot_client is not None: self.iot_client = iot_client if iot_client_token is not None: self.iot_client_token = iot_client_token log.info( "Created connection with iot-broker host:{}, path:{}, client:{}, token:{}" .format(self.host, self.__iot_broker_path, self.iot_client, self.iot_client_token)) url = self.__join_template.substitute(protocol=self.protocol, host=self.hostport, path=self.__iot_broker_path) querystring = { "token": self.iot_client_token, "clientPlatform": self.iot_client, "clientPlatformId": self.iot_clientId } headers = { RestHeaders.ACCEPT_STR.value: RestHeaders.APP_JSON.value, RestHeaders.CONT_TYPE.value: RestHeaders.APP_JSON.value } response = self.call(RestMethods.GET.value, url, headers, querystring) if response.status_code == 200: self.session_key = response.json()["sessionKey"] self.is_connected = True log.info("Logged correctly with session_key: {}".format( response.text)) self.add_to_debug_trace( "Logged correctly with session_key: {}".format(response.text)) else: log.info("Not possible to loggin: {} - {}".format( response.status_code, response.text)) self.add_to_debug_trace("Not possible to loggin: {} - {}".format( response.status_code, response.text)) return response
def raw_login(self, username=None, password=None, vertical=None): """ Login in the platform with User credentials @return response """ if username is not None: self.username = username if password is not None: self.password = password if vertical is not None: self.vertical = vertical log.info( "Created connection with controlpanel-auth host:{}, path:{}, username:{}, vertical:{}" .format(self.host, self.__control_panel_path, self.username, self.vertical)) url = self.__login_template.substitute(protocol=self.protocol, host=self.hostport, path=self.__control_panel_path) body = { "username": self.username, "password": self.password, "vertical": self.vertical } headers = { RestHeaders.ACCEPT_STR.value: RestHeaders.APP_JSON.value, RestHeaders.CONT_TYPE.value: RestHeaders.APP_JSON.value } response = self.call(RestMethods.POST.value, url, headers, body=body) if response.status_code == 200: self.token = Token.from_json(response.json()) log.info("Logged correctly, access token: {}".format(self.token)) self.add_to_debug_trace( "Logged correctly, access token: {}".format(self.token)) else: log.info("Not possible to login: {} - {}".format( response.status_code, response.text)) self.add_to_debug_trace("Not possible to login: {} - {}".format( response.status_code, response.text)) return response
def list(self, user): """ List APIs rest from user @param user user @return ok, info """ _ok = False _res = None try: log.info("Making list: user: {}".format(user)) self.raise_exception_if_not_token() url = self.__list_template.substitute(protocol=self.protocol, host=self.hostport, path=self.api_manager_path, user=user) headers = self.__headers response = self.call(RestMethods.GET.value, url, headers=headers) log.info("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) self.add_to_debug_trace("Response: {} - {}".format( response.status_code, response.text)) if response.status_code == 200: _res = response.json() log.info("Query result: {}".format(response.text)) self.add_to_debug_trace("Query result: {}".format( response.text)) _ok = True else: raise Exception("Response: {status_code} - {text}".format( status_code=response.status_code, text=response.text)) except Exception as e: log.error("Not possible to query api-manager: {exception}".format( exception=e)) self.add_to_debug_trace( "Not possible to query api-manager: {exception}".format( exception=e)) _res = e return _ok, _res
def raw_delete(self, ontology, entity_id, return_ids=True): """ Make a delete to iot-broker service of the platform @param ontology ontology name @param entity_id entity object id @param return_ids return ids in response (optional, default: True) @return response """ assert ontology != None, "Invalid input ontology" assert entity_id != None, "Invalid input entity_id" if return_ids: return_ids = "true" else: return_ids = "false" log.info("Making delete to ontology:{}, entity_id:{}".format( ontology, entity_id)) url = self.__delete_template.substitute(protocol=self.protocol, host=self.hostport, path=self.__iot_broker_path, ontology=ontology, entity=entity_id) params = {"ids": return_ids} headers = {RestHeaders.AUTHORIZATION.value: self.session_key} response = self.call(RestMethods.DELETE.value, url, headers=headers, params=params) if response.status_code != 200: log.info("Session expired, reconnecting...") is_reconnected, _ = self.restart() log.info("Reconnected: {}".format(is_reconnected)) self.add_to_debug_trace("Reconnected: {}".format(is_reconnected)) if is_reconnected: headers = {RestHeaders.AUTHORIZATION.value: self.session_key} response = self.call(RestMethods.DELETE.value, url, headers=headers, params=params) return response
def raw_insert(self, ontology, list_data): """ Make a insert to iot-broker service of the platform @param ontology ontology name @param list_data list with data to insert @return response """ assert ontology != None, "Invalid input ontology" assert list_data != None, "Invalid input list_data" if isinstance(list_data, str): list_data = json.loads(list_data) log.info("Making insert to ontology:{}, elements:{}".format( ontology, len(list_data))) url = self.__insert_template.substitute(protocol=self.protocol, host=self.hostport, path=self.__iot_broker_path, ontology=ontology) body = list_data headers = {RestHeaders.AUTHORIZATION.value: self.session_key} response = self.call(RestMethods.POST.value, url, headers=headers, body=body) if response.status_code != 200: log.info("Session expired, reconnecting...") is_reconnected, _ = self.restart() log.info("Reconnected: {}".format(is_reconnected)) self.add_to_debug_trace("Reconnected: {}".format(is_reconnected)) if is_reconnected: headers = {RestHeaders.AUTHORIZATION.value: self.session_key} response = self.call(RestMethods.POST.value, url, headers=headers, body=body) return response