Notatka
Dostęp do tej strony wymaga autoryzacji. Może spróbować zalogować się lub zmienić katalogi.
Dostęp do tej strony wymaga autoryzacji. Możesz spróbować zmienić katalogi.
API Fabric REST zapewnia punkt końcowy usług dla operacji CRUD dla elementów Fabric. W tym samouczku przedstawiamy kompleksowy scenariusz, jak stworzyć i zaktualizować element definicji pracy w Sparku. Obejmuje to trzy ogólne kroki:
- Stwórz element definicji zadania w Spark z pewnym stanem początkowym.
- Przekaż plik definicji głównej i inne pliki lib.
- Zaktualizuj element definicji zadania w Spark o adres URL OneLake głównego pliku definicji oraz innych plików lib.
Wymagania wstępne
- Token Microsoft Entra jest wymagany do uzyskania dostępu do interfejsu API REST Fabric. Zaleca się pobranie tokenu przez bibliotekę MSAL. Aby uzyskać więcej informacji, zobacz Obsługa przepływu uwierzytelniania w usłudze MSAL.
- Token magazynu jest wymagany do uzyskania dostępu do interfejsu API OneLake. Aby uzyskać więcej informacji, zobacz BIBLIOTEKA MSAL dla języka Python.
Stwórz element definicji zadania w Spark ze stanem początkowym
API Fabric REST definiuje zunifikowany punkt końcowy dla operacji CRUD dla elementów Fabric. Punkt końcowy to https://api.fabric.microsoft.com/v1/workspaces/{workspaceId}/items.
Szczegóły elementu są określone wewnątrz treści żądania. Oto przykład ciała żądania do tworzenia elementu definicji zadania w Sparku:
{
"displayName": "SJDHelloWorld",
"type": "SparkJobDefinition",
"definition": {
"format": "SparkJobDefinitionV1",
"parts": [
{
"path": "SparkJobDefinitionV1.json",
"payload": "<REDACTED>",
"payloadType": "InlineBase64"
}
]
}
}
W tym przykładzie element definicji zadania Spark nosi nazwę SJDHelloWorld. Pole payload to zakodowana w formacie base64 zawartość szczegółowej konfiguracji. Po dekodowaniu zawartość jest:
{
"executableFile":null,
"defaultLakehouseArtifactId":"",
"mainClass":"",
"additionalLakehouseIds":[],
"retryPolicy":null,
"commandLineArguments":"",
"additionalLibraryUris":[],
"language":"",
"environmentArtifactId":null
}
Poniżej przedstawiono dwie funkcje pomocnicze do kodowania i dekodowania szczegółowej konfiguracji:
import base64
def json_to_base64(json_data):
# Serialize the JSON data to a string
json_string = json.dumps(json_data)
# Encode the JSON string as bytes
json_bytes = json_string.encode('utf-8')
# Encode the bytes as Base64
base64_encoded = base64.b64encode(json_bytes).decode('utf-8')
return base64_encoded
def base64_to_json(base64_data):
# Decode the Base64-encoded string to bytes
base64_bytes = base64_data.encode('utf-8')
# Decode the bytes to a JSON string
json_string = base64.b64decode(base64_bytes).decode('utf-8')
# Deserialize the JSON string to a Python dictionary
json_data = json.loads(json_string)
return json_data
Oto fragment kodu do stworzenia elementu definicji zadania w Sparku:
import requests
bearerToken = "<REDACTED>" # Replace this token with the real AAD token
headers = {
"Authorization": f"Bearer {bearerToken}",
"Content-Type": "application/json" # Set the content type based on your request
}
payload = "<REDACTED>"
# Define the payload data for the POST request
payload_data = {
"displayName": "SJDHelloWorld",
"Type": "SparkJobDefinition",
"definition": {
"format": "SparkJobDefinitionV1",
"parts": [
{
"path": "SparkJobDefinitionV1.json",
"payload": payload,
"payloadType": "InlineBase64"
}
]
}
}
# Make the POST request with Bearer authentication
sjdCreateUrl = f"https://api.fabric.microsoft.com//v1/workspaces/{workspaceId}/items"
response = requests.post(sjdCreateUrl, json=payload_data, headers=headers)
Przekazywanie pliku definicji głównej i innych plików lib
Token magazynu jest wymagany do przekazania pliku do usługi OneLake. Oto funkcja pomocnika umożliwiająca uzyskanie tokenu magazynu:
import msal
def getOnelakeStorageToken():
app = msal.PublicClientApplication(
"<REDACTED>", # This field should be the client ID
authority="https://login.microsoftonline.com/microsoft.com")
result = app.acquire_token_interactive(scopes=["https://storage.azure.com/.default"])
print(f"Successfully acquired AAD token with storage audience:{result['access_token']}")
return result['access_token']
Teraz mamy utworzony element definicji pracy w Sparku. Aby można było go uruchomić, musimy skonfigurować główny plik definicji i wymagane właściwości. Punkt końcowy do przekazywania pliku dla tego elementu SJD to https://onelake.dfs.fabric.microsoft.com/{workspaceId}/{sjditemid}. Należy użyć tego samego identyfikatora obszaru roboczego z poprzedniego kroku. Wartość "sjditemid" można znaleźć w treści odpowiedzi poprzedniego kroku. Oto fragment kodu, który umożliwia skonfigurowanie pliku definicji głównej:
import requests
# Three steps are required: create file, append file, flush file
onelakeEndPoint = "https://onelake.dfs.fabric.microsoft.com/workspaceId/sjditemid" # Replace the ID of workspace and item with the right one
mainExecutableFile = "main.py" # The name of the main executable file
mainSubFolder = "Main" # The sub folder name of the main executable file. Don't change this value
onelakeRequestMainFileCreateUrl = f"{onelakeEndPoint}/{mainSubFolder}/{mainExecutableFile}?resource=file" # The URL for creating the main executable file via the 'file' resource type
onelakePutRequestHeaders = {
"Authorization": f"Bearer {onelakeStorageToken}", # The storage token can be achieved from the helper function above
}
onelakeCreateMainFileResponse = requests.put(onelakeRequestMainFileCreateUrl, headers=onelakePutRequestHeaders)
if onelakeCreateMainFileResponse.status_code == 201:
# Request was successful
print(f"Main File '{mainExecutableFile}' was successfully created in OneLake.")
# With the previous step, the main executable file is created in OneLake. Now we need to append the content of the main executable file
appendPosition = 0
appendAction = "append"
### Main File Append.
mainExecutableFileSizeInBytes = 83 # The size of the main executable file in bytes
onelakeRequestMainFileAppendUrl = f"{onelakeEndPoint}/{mainSubFolder}/{mainExecutableFile}?position={appendPosition}&action={appendAction}"
mainFileContents = "<REDACTED>" # The content of the main executable file, please replace this with the real content of the main executable file
mainExecutableFileSizeInBytes = 83 # The size of the main executable file in bytes, this value should match the size of the mainFileContents
onelakePatchRequestHeaders = {
"Authorization": f"Bearer {onelakeStorageToken}",
"Content-Type": "text/plain"
}
onelakeAppendMainFileResponse = requests.patch(onelakeRequestMainFileAppendUrl, data = mainFileContents, headers=onelakePatchRequestHeaders)
if onelakeAppendMainFileResponse.status_code == 202:
# Request was successful
print(f"Successfully accepted main file '{mainExecutableFile}' append data.")
# With the previous step, the content of the main executable file is appended to the file in OneLake. Now we need to flush the file
flushAction = "flush"
### Main File flush
onelakeRequestMainFileFlushUrl = f"{onelakeEndPoint}/{mainSubFolder}/{mainExecutableFile}?position={mainExecutableFileSizeInBytes}&action={flushAction}"
print(onelakeRequestMainFileFlushUrl)
onelakeFlushMainFileResponse = requests.patch(onelakeRequestMainFileFlushUrl, headers=onelakePatchRequestHeaders)
if onelakeFlushMainFileResponse.status_code == 200:
print(f"Successfully flushed main file '{mainExecutableFile}' contents.")
else:
print(onelakeFlushMainFileResponse.json())
Postępuj zgodnie z tym samym procesem, aby w razie potrzeby przekazać inne pliki lib.
Zaktualizuj element definicji zadania w Spark o adres URL OneLake głównego pliku definicji oraz innych plików lib
Do tej pory tworzyliśmy element definicji pracy w Spark z pewnym początkowym stanem i przesyłaliśmy główny plik definicji oraz inne pliki lib. Ostatnim krokiem jest aktualizacja elementu definicji zadania w Sparku, aby ustawić właściwości URL głównego pliku definicyjnego oraz innych plików lib. Punktem końcowym aktualizacji elementu https://api.fabric.microsoft.com/v1/workspaces/{workspaceId}/items/{sjditemid}definicji zadania w Spark jest . Należy używać tych samych "workspaceId" i "sjditemid" co w poprzednich krokach. Oto fragment kodu aktualizujący element definicji zadania w Spark:
mainAbfssPath = f"abfss://{workspaceId}@onelake.dfs.fabric.microsoft.com/{sjditemid}/Main/{mainExecutableFile}" # The workspaceId and sjditemid are the same as previous steps, the mainExecutableFile is the name of the main executable file
libsAbfssPath = f"abfss://{workspaceId}@onelake.dfs.fabric.microsoft.com/{sjditemid}/Libs/{libsFile}" # The workspaceId and sjditemid are the same as previous steps, the libsFile is the name of the libs file
defaultLakehouseId = '<REDACTED>' # Replace this with the real default lakehouse ID
updateRequestBodyJson = {
"executableFile": mainAbfssPath,
"defaultLakehouseArtifactId": defaultLakehouseId,
"mainClass": "",
"additionalLakehouseIds": [],
"retryPolicy": None,
"commandLineArguments": "",
"additionalLibraryUris": [libsAbfssPath],
"language": "Python",
"environmentArtifactId": None}
# Encode the bytes as a Base64-encoded string
base64EncodedUpdateSJDPayload = json_to_base64(updateRequestBodyJson)
# Print the Base64-encoded string
print("Base64-encoded JSON payload for SJD Update:")
print(base64EncodedUpdateSJDPayload)
# Define the API URL
updateSjdUrl = f"https://api.fabric.microsoft.com//v1/workspaces/{workspaceId}/items/{sjditemid}/updateDefinition"
updatePayload = base64EncodedUpdateSJDPayload
payloadType = "InlineBase64"
path = "SparkJobDefinitionV1.json"
format = "SparkJobDefinitionV1"
Type = "SparkJobDefinition"
# Define the headers with Bearer authentication
bearerToken = "<REDACTED>" # Replace this token with the real AAD token
headers = {
"Authorization": f"Bearer {bearerToken}",
"Content-Type": "application/json" # Set the content type based on your request
}
# Define the payload data for the POST request
payload_data = {
"displayName": "sjdCreateTest11",
"Type": Type,
"definition": {
"format": format,
"parts": [
{
"path": path,
"payload": updatePayload,
"payloadType": payloadType
}
]
}
}
# Make the POST request with Bearer authentication
response = requests.post(updateSjdUrl, json=payload_data, headers=headers)
if response.status_code == 200:
print("Successfully updated SJD.")
else:
print(response.json())
print(response.status_code)
Podsumowując cały proces, potrzebne są zarówno Fabric REST API, jak i OneLake API do stworzenia i aktualizacji elementu definicji zadania w Spark. API Fabric REST służy do tworzenia i aktualizacji elementu definicji zadania w Spark. Interfejs API OneLake służy do przekazywania głównego pliku definicji i innych plików lib. Główny plik definicji i inne pliki lib są najpierw przekazywane do usługi OneLake. Następnie właściwości URL głównego pliku definicyjnego oraz innych plików lib są ustawiane w elementie definicji zadania w Sparku.