def delete_workspaces(iam_apikey, url, version, workspace_ids, auth_type): """ Delete workspaces """ if auth_type == 'iam': authenticator = IAMAuthenticator(iam_apikey) elif auth_type == 'bearer': authenticator = BearerTokenAuthenticator(iam_apikey) else: raise ValueError(f'Unknown auth_type "{auth_type}"') for workspace_id in workspace_ids: if 'natural-language-classifier' in url: c = NaturalLanguageClassifierV1(authenticator=authenticator) c.set_service_url(url) c.delete_classifier(classifier_id=workspace_id) else: c = AssistantV1(version=version, authenticator=authenticator) c.set_service_url(url) c.delete_workspace(workspace_id=workspace_id) print('Cleaned up workspaces')
def get_notes(account_id, token, endpoint, providers): notes = [] try: findingsAPI = FindingsApiV1( authenticator=BearerTokenAuthenticator(token)) findingsAPI.set_service_url(endpoint) for provider in providers: response = findingsAPI.list_notes(account_id=account_id, provider_id=provider) if response.get_status_code() == 200: logger.info("got notes by provider: %s" % provider) for note in response.get_result()['notes']: notes.append(note) else: logger.error("unable to get notes by provider: %s" % provider) return notes except requests.exceptions.HTTPError as err: logger.exception( "an unexpected error was encountered while getting the note: " + str(err)) return False
import os from ibm_watson import DiscoveryV2 from ibm_watson.discovery_v2 import TrainingExample from ibm_cloud_sdk_core.authenticators import CloudPakForDataAuthenticator, BearerTokenAuthenticator ## Important: Discovery v2 is only available on Cloud Pak for Data. ## ## Authentication ## ## Option 1: username/password authenticator = CloudPakForDataAuthenticator('<your username>', '<your password>', '<url for authentication>', disable_ssl_verification=True) ## Option 2: bearer token authenticator = BearerTokenAuthenticator('your bearer token') ## Initialize discovery instance ## discovery = DiscoveryV2(version='2019-11-22', authenticator=authenticator) discovery.set_service_url('<service url>') discovery.set_disable_ssl_verification(True) PROJECT_ID = 'your project id' ## List Collections ## collections = discovery.list_collections(project_id=PROJECT_ID).get_result() print(json.dumps(collections, indent=2)) ## Component settings ## settings_result = discovery.get_component_settings( project_id=PROJECT_ID).get_result() print(json.dumps(settings_result, indent=2))
from ibm_watson.natural_language_understanding_v1 import Features, EntitiesOptions, KeywordsOptions, CategoriesOptions, ConceptsOptions, EmotionOptions, RelationsOptions, SemanticRolesOptions, SentimentOptions authenticator = IAMAuthenticator( 'mKzR3k6BF2W3tMUmoX3_Xvxze4LL0-f_q8FM5QMsFIFY') natural_language_understanding = NaturalLanguageUnderstandingV1( version='2019-07-12', authenticator=authenticator) from ibm_watson import IAMTokenManager iam_token_manager = IAMTokenManager( apikey='mKzR3k6BF2W3tMUmoX3_Xvxze4LL0-f_q8FM5QMsFIFY') token = iam_token_manager.get_token() from ibm_cloud_sdk_core.authenticators import BearerTokenAuthenticator # in the constructor, assuming control of managing the token authenticator1 = BearerTokenAuthenticator(token) natural_language_understanding1 = NaturalLanguageUnderstandingV1( version='2019-07-12', authenticator=authenticator1) f_name = input("enter file in csv format") x = 0 intext = [] with open("C:\\Users\\HP\\Desktop\\" + f_name + ".csv") as file: data = list(csv.reader(file)) #print(type(data[0])) strin = " ".join(str(x) for x in data) #print(type(strin)) #print(file) natural_language_understanding.set_service_url( 'https://api.eu-gb.natural-language-understanding.watson.cloud.ibm.com/instances/c70c1850-5873-495c-b449-d84d30415f06' ) natural_language_understanding.set_disable_ssl_verification(True)
def run_module(): module = AnsibleModule(argument_spec=module_args, supports_check_mode=False) # New resource required arguments checks missing_args = [] for arg, _ in REQUIRED_PARAMETERS: if module.params[arg] is None: missing_args.append(arg) if missing_args: module.fail_json(msg=("missing required arguments: " + ", ".join(missing_args))) if not module.params["instance_ip"] and not module.params["instance_id"]: module.fail_json(msg=( "missing required arguments: pass instance_ip or instance_id")) # authenticate using api-key if module.params["ibmcloud_api_key"]: authenticator = IAMAuthenticator(module.params["ibmcloud_api_key"]) elif module.params["bearer_token"]: authenticator = BearerTokenAuthenticator(module.params["bearer_token"]) else: authenticator = BearerTokenAuthenticator( module.params["env_bearer_token"]) service = VpcV1('2020-06-02', authenticator=authenticator) instanceId = module.params["instance_id"] if module.params["instance_ip"]: try: floatingIps = service.list_floating_ips().get_result( )['floating_ips'] instances = service.list_instances().get_result()['instances'] except ApiException as e: print("List instances/floatingIp failed with status code " + str(e.code) + ": " + e.message) target = "" for floatingIp in floatingIps: if floatingIp["address"] == module.params["instance_ip"]: target = floatingIp["target"]["id"] for instance in instances: if target == "": if instance["primary_network_interface"][ "primary_ipv4_address"] == module.params[ "instance_ip"]: instanceId = instance["id"] # print(instance['id'], "\t", instance['name']) elif instance["primary_network_interface"]["id"] == target: instanceId = instance["id"] # print(instance['id'], "\t", instance['name']) if instanceId == "": module.fail_json(msg=("instance not found")) try: stopIns = service.create_instance_action( instance_id=instanceId, type=module.params["action_type"]) except ApiException as e: module.fail_json(msg=("Failed to get expected response")) print("stop instances failed with status code " + str(e.code) + ": " + e.message) #print(stopIns) if stopIns.get_status_code() != 201: module.fail_json(msg=("Failed to get expected response")) module.exit_json(**stopIns.get_result())
def test_bearer_validate_failed(): with pytest.raises(ValueError) as err: BearerTokenAuthenticator(None) assert str(err.value) == 'The bearer token shouldn\'t be None.'