コードの例Foundry APIローカル環境

注: 以下の翻訳の正確性は検証されていません。AIPを利用して英語版の原文から機械的に翻訳されたものです。

ローカル環境

Python

リソースをプロジェクトに追加する

API 呼び出しを使用してリソースをプロジェクトに追加するにはどうすればよいですか?

このコードは requests ライブラリを使用して Compass API に HTTP POST リクエストを送信し、アーティファクトへの参照を指定されたプロジェクトにインポートします。エラー処理、ログ記録、および任意のプロキシ設定が含まれています。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 from requests.adapters import HTTPAdapter import requests from urllib3 import Retry import logging import json ''' Import a reference to an artifact as a reference to the project specified ''' # Headers headers = { 'Authorization': 'Bearer xxx', # Replace 'xxx' with your bearer token 'Content-Type': 'application/json', } # Host host = 'subdomain.domain.extension:port' # Proxies proxyDict = { 'https': 'protocol://subdomain.domain.extension:port' } # Retries retry = Retry(connect=1, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) http = requests.Session() http.mount('https://', adapter) # Set the level of logging to be shown logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler("debug.log"), logging.StreamHandler() ] ) ############### ## VARIABLES ## ############### RESSOURCE_TO_ADD = "ri......" PROJECT_TO_ADD_TO = "ri.compass.main.folder.xxxx-xxx-xxx-xxx-xxxx" # Throw an error if request fails in some way with information about it try: print(f'Beginning script for ...') # Data source_data = { "requests": [ {"resourceRid": f"{RESSOURCE_TO_ADD}"} ] } # Serialize the JSON data = json.dumps(source_data) response = http.post(f'https://{host}/compass/api/projects/imports/{PROJECT_TO_ADD_TO}/import', data=data, headers=headers, # Uncomment if a proxy is required # proxies=proxyDict ) print('Completed request') print(f'The result of the script is ...') raw_response = response.text print(raw_response) print(response.status_code) except requests.exceptions.RequestException as e: raise Exception( f"An error occurred in the request.\nIt failed due to: {response.status_code} - {response.text}\nException: {e}")
  • 送信日: 2024-03-26
  • タグ: API, python, compass

データセットの行数

多数のデータセットの行数を一括で計算するにはどうすればよいですか?

このコードは Foundry API を使用して、データセット RID のリストに対する行数計算を開始し、その結果を読み取ります。計算はバッチ処理できないため、データセット RID とブランチをパラメーターとして、データセットごとに1件の POST リクエストを Foundry Stats API に送信します。各 POST リクエストは計算をキューに入れるだけで、行数ではなく、解決されたデータセットビューを返します。その後、バッチエンドポイントに1件の POST リクエストを送信して、すべての結果を読み取ります。このエンドポイントはデータセット RID とブランチのペアのリストを受け取り、リクエストごとに1件のレスポンスを同じ順序で返します。非常に大きなリストは、小さなバッチに分割してください。計算は非同期で行われ、大きなデータセットでは1分以上かかることがあるため、各データセットの status が SUCCEEDED になるまでバッチリクエストを繰り返してください。以下のコードは、読み取りの間に1分間待機します。ステータス ABSENT、PENDING、RUNNING は行数がまだ利用可能でないことを意味し、FAILED は計算によって行数が生成されないことを意味します。返される rowCount は数値ではなくラッパーオブジェクトであり、正確に計算された件数は exactValue.value で Decimal の文字列表現として取得できます。

Foundry はデータセットのビルド中にも統計情報を記録しますが、その収集はベストエフォートです。ビルド自体は失敗せずに、統計情報の収集がタイムアウトしたり、失敗したりすることがあるため、一部のデータセットにはビルド時の行数がありません。以下に示す方法で計算を開始すると、統計情報が記録されていないデータセットの行数が生成されます。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 from shutil import ExecError from wsgiref import headers import requests from urllib3 import Retry import json import pprint import time ''' 指定されたデータセット RID に対して行数の計算を開始するスクリプトです ''' # 基本変数 base_url = "https://STACK_NAME.palantircloud.com" branch = "master" DATASETS_RIDS = [ "ri.foundry.main.dataset.6d2cd3de-0052-xxxxx-c7ae2c4ab1d8" ] headers = { 'Authorization': 'Bearer eyg_PUT_YOUR_TOKEN_HERE_xxxx', 'Content-Type': 'application/json' } # プロキシ proxyDict = { # "https": "https://proxyIfNeeded:port" } # 再試行 retry = Retry(connect=1, backoff_factor=0.5) adapter = requests.adapters.HTTPAdapter(max_retries=retry) http = requests.Session() http.mount("https://", adapter) def trigger_row_count(dataset_rid, branch): response = http.post(f'{base_url}/foundry-stats/api/stats/datasets/{dataset_rid}/branches/{branch}', headers=headers, proxies=proxyDict) raw_response = response.text curr_response = json.loads(raw_response) pprint.pprint(curr_response) return curr_response def get_row_counts(dataset_rids, branch, attempts=12, delay=60): row_counts = {} pending_rids = list(dataset_rids) for _ in range(attempts): stats_requests = [{'datasetRid': pending_rid, 'branch': branch} for pending_rid in pending_rids] response = http.post(f'{base_url}/foundry-stats/api/stats/batch/stats', headers=headers, proxies=proxyDict, data=json.dumps(stats_requests)) if not response.ok: print(f"Could not read row counts: {response.text}") return row_counts # バッチエンドポイントは、リクエストの送信順に、リクエストごとに1件のレスポンスを返します。 still_pending_rids = [] for dataset_rid, curr_response in zip(pending_rids, json.loads(response.text)): status = curr_response['status'] if status == 'SUCCEEDED': result = curr_response['result'] row_counts[dataset_rid] = result[result['type']]['stats']['rowCount'] elif status == 'FAILED': print(f"Row count computation failed for {dataset_rid}") else: still_pending_rids.append(dataset_rid) pending_rids = still_pending_rids if not pending_rids: break time.sleep(delay) for pending_rid in pending_rids: print(f"Row count for {pending_rid} is still not ready") pprint.pprint(row_counts) return row_counts for curr_dataset_rid in DATASETS_RIDS : trigger_row_count(curr_dataset_rid, branch) get_row_counts(DATASETS_RIDS, branch)
  • 送信日: 2024-03-26
  • タグ: export, python, metrics, metadata, local

データセット全体の列のスーパーセットを取得する

複数のデータセットにわたるすべての列の集合を取得するにはどうすればよいですか?

このコードは requests ライブラリを使用して、対象データセットのリストに含まれる各データセットのスキーマを取得します。その後、スキーマ内のフィールドを反復処理し、列のスーパーセットにおける各列の出現頻度を格納した辞書を作成します。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 import time from requests.packages.urllib3.util.retry import Retry from requests.adapters import HTTPAdapter import requests import json import pprint import logging import datetime import collections ''' データセット群から、列のスーパーセットとその出現頻度を生成するスクリプトです ''' headers = { 'Authorization': 'Bearer eyg_PUT_YOUR_TOKEN_HERE_xxxx', 'Content-Type': 'application/json', } ## STACK_NAME base_url = "STACK_NAME.palantircloud.com" branch = "master" target_datasets = ["ri.foundry.main.dataset.4c2ac089-xxxx-4df863eaf823"] # プロキシ proxyDict = { #"https": "https://proxyIfNeeded:port" } # 再試行 retry = Retry(connect=1, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) http = requests.Session() http.mount("https://", adapter) global_list_fields = {} for curr_dataset in target_datasets : # データセットのスキーマを取得します print(f"Step 1. Get Schema of dataset") response = http.get(f'{base_url}/foundry-metadata/api/schemas/datasets/{curr_dataset}/branches/{branch}', headers=headers, proxies=proxyDict) print(f"Step 1. Response of getting schema of dataset") raw_response = response.text print(raw_response) curr_schema = json.loads(raw_response) list_fields = curr_schema["schema"]["fieldSchemaList"] for field in list_fields: curr_key = f"{field['name']} - {field['type']}" # カウンターを増やします global_list_fields[curr_key] = global_list_fields.get(curr_key, 0) + 1 print("Unsorted dict") pprint.pprint(global_list_fields) # 並べ替えます sorted_dict = {k: v for k, v in sorted(global_list_fields.items(), key=lambda item: item[1])} print("Sorted dict") pprint.pprint(sorted_dict)
  • 送信日: 2024-03-26
  • タグ: python, API, metadata, code repositories, code authoring, local

OSS の直接呼び出し

Object Set Service(OSS)を使用してオブジェクトセットの集計を行うにはどうすればよいですか?

このコードは、Object Set Service(OSS)を直接呼び出してオブジェクトセットの集計を行う方法を示します。オントロジー SDK やフロントエンドなどのほかのサービスで使用される OSS が返すデータのデバッグや理解に役立ちます。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 from requests.adapters import HTTPAdapter import requests from urllib3 import Retry import logging import json import pprint ''' Direct calls to object-set-service (OSS) to perform aggregations, etc. This is not intended for "actual use" in production, but can be useful for debugging or going one layer deeper, for instance to debug or understand what is actually returned by OSS. OSS is used under the hood by other services, like OSDK and frontends. ''' # Headers headers = { 'Authorization': 'Bearer xxx', # Replace 'xxx' with your bearer token 'Content-Type': 'application/json', } # Host host = 'subdomain.domain.extension:port' # Proxies proxyDict = { 'https': 'protocol://subdomain.domain.extension:port' } # Retries retry = Retry(connect=1, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) http = requests.Session() http.mount('https://', adapter) # Set the level of logging to be shown logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler("debug.log"), logging.StreamHandler() ] ) ############### ## VARIABLES ## ############### # Throw an error if request fails in some way with information about it try: print(f'Beginning script for ...') # Data - Example payload to OSS data = { "executionMode":"PREFER_ACCURACY", # OSS will default to "PREFER_SPEED" which can provide inaccurate results "objectSet": { "base": { "objectTypeId": "af-20m-instances-obv2" # The object instance id }, "type": "base" }, "aggregation": { "metrics": {}, "subAggregations": { "test": { "type": "metrics", "metrics": { "dimension": { "type": "propertyValue", "propertyValue": { "propertyId": "example_bucket", # The property of the object to aggregate by "bucketing": { "type": "exactValue", "exactValue": { "maxBuckets": 10 # The number of buckets the response should contain } } } }, "ordering": [ { "type": "valueOrdering", "valueOrdering": { "direction": "DESCENDING", "metricName": "countM" } } ], "metrics": { "countM": { "type": "count", "count": {} } } } } } } } # Serialize the JSON data = json.dumps(source_data) response = http.put(f'https://{host}/object-set-service/api/aggregate', data=data, headers=headers, # Uncomment if a proxy is required # proxies=proxyDict ) print('Completed request') print(f'The result of the script is ...') pprint.pprint(response.json()) except requests.exceptions.RequestException as e: raise Exception(f"An error occurred in the request.\nIt failed due to: {response.status_code} - {response.text}\nException: {e}")
  • 送信日: 2024-03-26
  • タグ: ontology, aggregation, objects, python, API, local

Foundry に ping を送信する:トークン不要

認証トークンなしで Foundry インスタンスやアカウントに ping を送信するにはどうすればよいですか?

このコードは、Python の requests ライブラリを使用して、指定されたプロキシと再試行設定で Palantir Cloud Stack に ping リクエストを送信する方法を示します。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 from requests.packages.urllib3.util.retry import Retry from requests.adapters import HTTPAdapter import requests headers = { # On principle : no token required ! 'Authorization': 'Bearer eyg_PUT_YOUR_TOKEN_HERE_xxxx', 'Content-Type': 'application/json', } ## STACK base_url = "https://STACK_NAME.palantircloud.com" # Proxies proxyDict = { "https": "http://proxy.host.com:3333" } # Retries retry = Retry(connect=1, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) http = requests.Session() http.mount("https://", adapter) print("Pinging ... ") response = http.get(f"{base_url}/compass/api/ping", headers=headers, proxies=proxyDict) print("Ping response :") raw_response = response.text print(raw_response)
  • 送信日: 2024-03-26
  • タグ: API, python, compass, local

指定されたリソース RID のパスを取得する

リソースの RID からそのパスを見つけるにはどうすればよいですか?

このコードは requests ライブラリを使用して、指定された RID を含む HTTP GET リクエストを指定されたホストに送信し、リソースのパスを取得します。再試行とプロキシも処理します。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 from requests.adapters import HTTPAdapter import requests from urllib3 import Retry ''' Script to return the path of a given Resource IDentifier (RID). ''' # Headers headers = { 'Authorization': 'Bearer xxx', # Replace 'xxx' with your bearer token 'Content-Type': 'application/json', } # Host host = 'host.com:443' # Proxies proxyDict = { 'https': 'http://proxy.domain.com:3333' } # Retries retry = Retry(connect=1, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) http = requests.Session() http.mount('https://', adapter) # Enter the rid of the resource you want the path of RESOURCE_RID = '' # Throw an error if the reference has failed to be created try: print(f'Fetching path for rid {RESOURCE_RID} ...') response = http.get(f'https://{host}/compass/api/resources/{RESOURCE_RID}/path-json', headers=headers, proxies=proxyDict) print('Completed request') print(f'The path is: {response.text}') except requests.exceptions.RequestException as e: raise Exception(f"An error occurred in the request.\nReturning the path for the repository: {RESOURCE_RID} failed due to: {response.status_code} - {response.text}\nException: {e}")
  • 送信日: 2024-03-26
  • タグ: api, python, metadata, local

API を使用してアクションを開始する

オブジェクトに対するアクションを手動で開始するにはどうすればよいですか?

このコードは requests ライブラリを使用してアクション API に HTTP リクエストを送信し、ID のリストを反復処理して、カスタムパラメーターを指定したアクションを各 ID に対して開始します。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 from requests.packages.urllib3.util.retry import Retry from requests.adapters import HTTPAdapter import pprint import uuid import requests import json import time ''' Script that will trigger an action. ''' headers = { 'Authorization': 'Bearer eyg_PUT_YOUR_TOKEN_HERE_xxxx', 'Content-Type': 'application/json' } # Name of the stack STACK = "STACK_NAME.palantircloud.com" # List of ids, could be any list of parameters you want to iterate on list_ids = ["123", "456"] # Proxies proxyDict = { "https": "https://proxyIfNeeded:port" } # Retries retry = Retry(connect=1, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) http = requests.Session() http.mount("https://", adapter) # Iterate over the list of ids and trigger one action per ID. for curr_id in list_ids: curr_uuid = "GENERATED-OBJECT-" + str(uuid.uuid4()) # To generate a uuid curr_title = "GENERATED-" + str(time.time()) # To generate a timestamp user_rid = "xxxxxx-xxxx-xxxx-xxxx-xxxxxxxxx" # if a user rid is needed try: # Generate the payload of the action. Look at a network tab from slate/Workshop to obtain it - or build it from scratch. payload = r'{"actionTypeRid":"ri.actions.main.action-type.xxxxx-xxxx-xxxx-xxxxxxxx",' \ r'"parameters":{"ri.actions.main.parameter.xxxxx-xxxx-xxxx-xxxxxxxx":{"timestamp":"2021-09-30T23:59:59+02:00","type":"timestamp"},' \ r'"ri.actions.main.parameter.xxxxx-xxxx-xxxx-xxxxxxxx":{"stringList":{"strings":["mystring1","mystring2"]},"type":"stringList"},' \ r'"ri.actions.main.parameter.xxxxx-xxxx-xxxx-xxxxxxxx":{"string":"my_string","type":"string"},' \ r'"ri.actions.main.parameter.xxxxx-xxxx-xxxx-xxxxxxxx":{"timestamp":"2022-01-01:23:26+00:00","type":"timestamp"}}' response = http.post(f'https://{STACK}/actions/api/actions', headers=headers, proxies=proxyDict, data=payload) print(f"Raw response of action call with : {curr_id}\r\n") raw_response = response.json() pprint.pprint(raw_response, indent=4) except Exception as e: print(e)
  • 送信日: 2024-03-26
  • タグ: action, objects, ontology, actions on objects, python, api, local

ローカルファイルをデータセットにアップロードする

Foundry のデータセットにローカルファイルをアップロードするには、どの API を使用できますか?

このコードは Foundry API を使用して、指定されたデータセットにファイルをアップロードします。リクエストのヘッダー、ホスト、プロキシ、および再試行を設定した後、ファイルを読み取り、データセットの files エンドポイントに POST リクエストとして送信します。

Copied!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 from requests.adapters import HTTPAdapter import requests from urllib3 import Retry import logging import json # Headers headers = { 'Authorization': 'Bearer xxx', # Replace 'xxx' with your bearer token 'Content-type': 'application/octet-stream', ### IMPORTANT ! } # Host host = 'subdomain.domain.extension:port' # Proxies proxyDict = { 'https': 'protocol://subdomain.domain.extension:port' } # Retries retry = Retry(connect=1, backoff_factor=0.5) adapter = HTTPAdapter(max_retries=retry) http = requests.Session() http.mount('https://', adapter) # Set the level of logging to be shown logging.basicConfig( level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s", handlers=[ logging.FileHandler("debug.log"), logging.StreamHandler() ] ) ############### ## VARIABLES ## ############### # Dataset RID to upload to datasetRid = "rid.123..." params = { 'filePath': 'folder_name/my-file.csv', } # Throw an error if request fails in some way with information about it try: print(f'Beginning script for one-call upload') # Data with open('./data_example_file.csv') as f: data = f.read().replace('\n', '').replace('\r', '').encode() response = http.post(f'https://{host}/api/v1/datasets/{datasetRid}/files:upload', params=params, data=data, headers=headers, # Uncomment if a proxy is required # proxies=proxyDict ) print('Completed request') print(f'The result of the script is {response.status_code} - {response.text}') except requests.exceptions.RequestException as e: raise Exception( f"An error occurred in the request.\nIt failed due to: {response.status_code} - {response.text}\nException: {e}")
  • 送信日: 2024-04-04
  • タグ: API, file upload, dataset, python, csv, local