Catatan
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba masuk atau mengubah direktori.
Akses ke halaman ini memerlukan otorisasi. Anda dapat mencoba mengubah direktori.
Gunakan notebookutils.notebook untuk mengelola item notebook secara terprogram di Microsoft Fabric. Anda dapat membuat, mengambil, memperbarui, menghapus, dan mencantumkan artefak notebook untuk mengotomatiskan penyebaran, manajemen siklus hidup, dan alur kerja CI/CD.
Nota
API ini hanya didukung di notebook Fabric, bukan di Azure Synapse. Anda harus memiliki izin yang sesuai di ruang kerja target untuk setiap operasi.
Tabel berikut ini mencantumkan metode manajemen buku catatan yang tersedia:
| Metode | Signature | Deskripsi |
|---|---|---|
create |
create(name, description, content, defaultLakehouse, defaultLakehouseWorkspace, workspaceId): Artifact |
Membuat buku catatan baru. |
get |
get(name, workspaceId): Artifact |
Mengambil buku catatan berdasarkan nama atau ID. |
getDefinition |
getDefinition(name, workspaceId, format): String |
Mengambil definisi buku catatan (konten). |
update |
update(name, newName, description, workspaceId): Artifact |
Memperbarui metadata buku catatan. |
updateDefinition |
updateDefinition(name, content, defaultLakehouse, defaultLakehouseWorkspace, workspaceId, environmentId, environmentWorkspaceId): bool |
Memperbarui definisi notebook dan lakehouse. |
delete |
delete(name, workspaceId): Boolean |
Menghapus buku catatan. |
list |
list(workspaceId, maxResults): Array[Artifact] |
Menampilkan semua buku catatan yang ada di lingkungan kerja. |
Membuat buku catatan
Gunakan notebookutils.notebook.create() untuk membuat artefak buku catatan baru di ruang kerja saat ini atau ruang kerja tertentu.
Nota
Contoh alur kerja dalam artikel ini yang membaca atau menulis .ipynb file menggunakan Python untuk I/O file. API inti notebookutils.notebook tersedia di Python, PySpark, Scala, dan R kecuali dinyatakan lain.
Parameter-parameternya
| Parameter | Tipe | Required | Deskripsi |
|---|---|---|---|
name |
string | Yes | Tampilkan nama untuk buku catatan baru. Harus unik di dalam ruang kerja. |
description |
string | No | Deskripsi buku catatan. Default untuk kosong. |
content |
String, byte, atau kamus | Yes | Konten buku catatan dalam format JSON yang valid .ipynb . Bisa juga byte mentah atau objek dict.
Tidak boleh kosong. |
defaultLakehouse |
string | No | Nama atau ID lakehouse default yang akan dilampirkan. |
defaultLakehouseWorkspace |
string | No | ID Ruang Kerja dari lakehouse yang disetel sebagai default. Biarkan kosong untuk ruang kerja saat ini. |
workspaceId |
string | No | ID ruang kerja target. Biarkan kosong untuk ruang kerja saat ini. |
Penting
Parameter content tidak boleh kosong. Anda harus menyediakan konten format yang valid .ipynb saat membuat buku catatan. Setidaknya, sediakan struktur notebook kosong yang valid:
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}
Membuat buku catatan dari templat
# Read notebook template from a file
with open("/path/to/template.ipynb", "r") as f:
notebook_content = f.read()
# Create the notebook
notebook = notebookutils.notebook.create(
name="ProcessingNotebook",
description="Data processing notebook from template",
content=notebook_content
)
print(f"Created notebook: {notebook.displayName} (ID: {notebook.id})")
Buat buku catatan dengan lakehouse default
# Minimum valid notebook content - content cannot be empty
minimal_content = '''{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 5
}'''
# Create notebook with default lakehouse configuration
notebook = notebookutils.notebook.create(
name="DataAnalysis",
description="Analysis notebook with lakehouse access",
content=minimal_content,
defaultLakehouse="MyLakehouse",
defaultLakehouseWorkspace="" # Current workspace
)
print(f"Created notebook with lakehouse: {notebook.displayName}")
Mengembalikan nilai
Metode create() mengembalikan Artifact objek dengan properti berikut:
-
displayName: Nama tampilan buku catatan. -
id: Pengidentifikasi unik notebook yang dibuat. -
description: Deskripsi buku catatan.
Membuat buku catatan di ruang kerja lain
with open("/path/to/notebook.ipynb", "r") as f:
content = f.read()
notebook = notebookutils.notebook.create(
name="SharedNotebook",
description="Notebook for the shared workspace",
content=content,
workspaceId="bbbbbbbb-2222-3333-4444-cccccccccccc"
)
print(f"Created in remote workspace: {notebook.displayName}")
Membuat beberapa buku catatan dari templat
# Load template content (must be valid .ipynb)
with open("/path/to/template.ipynb", "r") as f:
template_content = f.read()
regions = ["US", "EU", "Asia"]
created_notebooks = []
for region in regions:
notebook = notebookutils.notebook.create(
name=f"Process_{region}",
description=f"Processing notebook for {region} region",
content=template_content,
defaultLakehouse=f"Lakehouse_{region}"
)
created_notebooks.append(notebook)
print(f"Created: {notebook.displayName}")
print(f"\nCreated {len(created_notebooks)} notebooks")
Tip
Berikan nama dan deskripsi yang bermakna bagi buku catatan Anda agar lebih mudah ditemukan. Gunakan konvensi penamaan yang konsisten seperti <Project>_<Purpose>_<Region> untuk penyebaran otomatis.
Mendapatkan buku catatan
Gunakan notebookutils.notebook.get() untuk mengambil metadata buku catatan berdasarkan nama atau ID. Ini mengembalikan Artifact objek dengan properti seperti displayName, , iddan description.
Parameter-parameternya
| Parameter | Tipe | Required | Deskripsi |
|---|---|---|---|
name |
string | Yes | Nama atau ID buku catatan yang akan diambil. |
workspaceId |
string | No | ID Ruang Kerja. Biarkan kosong untuk ruang kerja saat ini. |
Dapatkan buku catatan dari workspace saat ini
notebook = notebookutils.notebook.get("MyNotebook")
print(f"Notebook Name: {notebook.displayName}")
print(f"Notebook ID: {notebook.id}")
print(f"Description: {notebook.description}")
Mendapatkan buku catatan dari ruang kerja lain
workspace_id = "bbbbbbbb-2222-3333-4444-cccccccccccc"
notebook = notebookutils.notebook.get("SharedNotebook", workspaceId=workspace_id)
print(f"Retrieved: {notebook.displayName} from workspace {workspace_id}")
Mengembalikan nilai
Metode get() mengembalikan Artifact objek dengan properti berikut:
-
displayName: Nama tampilan buku catatan. -
id: Pengidentifikasi unik. -
description: Deskripsi buku catatan.
Tip
Gunakan get() sebelum memperbarui atau menghapus operasi untuk memverifikasi bahwa buku catatan target ada. Anda juga bisa menggunakannya untuk memeriksa apakah nama buku catatan sudah digunakan sebelum Anda membuat yang baru.
Mendapatkan definisi buku catatan
Gunakan notebookutils.notebook.getDefinition() untuk mengambil konten buku catatan lengkap dalam .ipynb format. Gunakan untuk pencadangan, migrasi, kontrol versi, atau analisis konten.
Parameter-parameternya
| Parameter | Tipe | Required | Deskripsi |
|---|---|---|---|
name |
string | Yes | Nama atau ID buku catatan. |
workspaceId |
string | No | ID Ruang Kerja. Biarkan kosong untuk ruang kerja saat ini. |
format |
string | No | Format output. Secara default menjadi "ipynb". |
Mengambil dan menyimpan definisi buku catatan
# Retrieve notebook definition as .ipynb content
notebook_content = notebookutils.notebook.getDefinition("MyNotebook")
# Save to a file for backup
with open("/path/to/backup/MyNotebook.ipynb", "w") as f:
f.write(notebook_content)
print("Notebook definition retrieved and saved")
Mendapatkan definisi buku catatan dari ruang kerja lain
workspace_id = "cccccccc-3333-4444-5555-dddddddddddd"
notebook_content = notebookutils.notebook.getDefinition(
name="SharedNotebook",
workspaceId=workspace_id,
format="ipynb"
)
print(f"Retrieved definition from workspace {workspace_id}")
Mengembalikan nilai
Metode mengembalikan getDefinition() string yang berisi konten buku catatan dalam .ipynb format JSON.
Ekspor semua buku catatan untuk pencadangan
import os
from datetime import datetime
def export_all_notebooks(backup_dir="/path/to/backups"):
"""Export all notebooks in the workspace for backup."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
export_dir = f"{backup_dir}/backup_{timestamp}"
os.makedirs(export_dir, exist_ok=True)
notebooks = notebookutils.notebook.list()
print(f"Exporting {len(notebooks)} notebooks to {export_dir}")
exported_count = 0
for nb in notebooks:
try:
content = notebookutils.notebook.getDefinition(nb.displayName)
filename = f"{export_dir}/{nb.displayName}.ipynb"
with open(filename, "w") as f:
f.write(content)
exported_count += 1
print(f"Exported: {nb.displayName}")
except Exception as e:
print(f"Failed to export {nb.displayName}: {e}")
print(f"\nExported {exported_count} of {len(notebooks)} notebooks")
return export_dir
backup_location = export_all_notebooks()
Memperbarui buku catatan
Gunakan notebookutils.notebook.update() untuk mengubah metadata buku catatan, seperti nama tampilan dan deskripsinya. Ini tidak mengubah konten buku catatan maupun konfigurasi lakehouse.
Parameter-parameternya
| Parameter | Tipe | Required | Deskripsi |
|---|---|---|---|
name |
string | Yes | Nama atau ID buku catatan saat ini. |
newName |
string | Yes | Nama tampilan baru untuk buku catatan. |
description |
string | No | Deskripsi yang diperbarui. |
workspaceId |
string | No | ID Ruang Kerja. Biarkan kosong untuk ruang kerja saat ini. |
Mengganti nama buku catatan
updated_notebook = notebookutils.notebook.update(
name="OldNotebookName",
newName="NewNotebookName",
description="Updated description with more details"
)
print(f"Updated notebook: {updated_notebook.displayName}")
Mengembalikan nilai
Metode update() mengembalikan Artifact objek dengan properti yang diperbarui.
Memperbarui definisi buku catatan
Gunakan notebookutils.notebook.updateDefinition() untuk mengubah konten buku catatan, lakehouse bawaan, atau keduanya. Gunakan saat Anda perlu mengubah definisi buku catatan daripada metadatanya.
Parameter-parameternya
| Parameter | Tipe | Required | Deskripsi |
|---|---|---|---|
name |
string | Yes | Nama atau ID buku catatan yang akan diperbarui. |
content |
string | No | Konten buku catatan baru dalam .ipynb format. |
defaultLakehouse |
string | No | Nama lakehouse default baru. |
defaultLakehouseWorkspace |
string | No | ID ruang kerja lakehouse default baru. Biarkan kosong untuk ruang kerja saat ini. |
workspaceId |
string | No | ID Ruang Kerja. Biarkan kosong untuk ruang kerja saat ini. |
environmentId |
string | No | ID Lingkungan untuk dilampirkan ke buku catatan. |
environmentWorkspaceId |
string | No | ID Ruang Kerja untuk Lingkungan. Biarkan kosong untuk ruang kerja saat ini. |
Nota
Parameter environmentId dan environmentWorkspaceId hanya tersedia di runtime notebook Spark. Notebook Python tidak mendukung parameter ini.
Memperbarui konten buku catatan
# Load new content
with open("/path/to/updated_notebook.ipynb", "r") as f:
new_content = f.read()
is_updated = notebookutils.notebook.updateDefinition(
name="MyNotebook",
content=new_content
)
print(f"Notebook definition updated: {is_updated}")
Mengubah default lakehouse
is_updated = notebookutils.notebook.updateDefinition(
name="MyNotebook",
defaultLakehouse="NewLakehouse",
defaultLakehouseWorkspace="" # Current workspace
)
print(f"Default lakehouse updated: {is_updated}")
Perbarui konten dan lakehouse
with open("/path/to/new_version.ipynb", "r") as f:
new_content = f.read()
is_updated = notebookutils.notebook.updateDefinition(
name="MyNotebook",
content=new_content,
defaultLakehouse="ProductionLakehouse",
defaultLakehouseWorkspace=""
)
print(f"Notebook fully updated: {is_updated}")
Mengembalikan nilai
Metode updateDefinition() mengembalikan True jika pembaruan berhasil atau False jika gagal.
Tip
Gunakan update() untuk perubahan metadata (nama, deskripsi), dan updateDefinition() untuk perubahan konten serta lakehouse. Saat Anda memerlukan refresh penuh metadata dan konten, panggil kedua metode secara berurutan.
Menghapus buku catatan
Gunakan notebookutils.notebook.delete() untuk menghapus buku catatan secara permanen dari ruang kerja. Ini mengembalikan True jika penghapusan berhasil; jika tidak, itu mengembalikan False.
Parameter-parameternya
| Parameter | Tipe | Required | Deskripsi |
|---|---|---|---|
name |
string | Yes | Nama atau ID buku catatan yang akan dihapus. |
workspaceId |
string | No | ID Ruang Kerja. Biarkan kosong untuk ruang kerja saat ini. |
Penting
Penghapusan bersifat permanen. Buku catatan yang dihapus tidak dapat dipulihkan. Selalu verifikasi nama buku catatan sebelum Anda menghapus, dan pertimbangkan untuk mencadangkan definisi buku catatan dengan getDefinition() terlebih dahulu.
Mengembalikan nilai
Metode delete() mengembalikan True jika penghapusan berhasil atau False jika gagal.
Menghapus buku catatan
is_deleted = notebookutils.notebook.delete("ObsoleteNotebook")
if is_deleted:
print("Notebook deleted successfully")
else:
print("Failed to delete notebook")
Membersihkan notebook dengan aman berdasarkan pola
def cleanup_notebooks(name_pattern, dry_run=True):
"""Delete notebooks matching a name pattern."""
notebooks = notebookutils.notebook.list()
to_delete = [nb for nb in notebooks if name_pattern in nb.displayName]
print(f"Found {len(to_delete)} notebooks matching '{name_pattern}':")
for nb in to_delete:
print(f" - {nb.displayName}")
if dry_run:
print("\nDRY RUN - No notebooks deleted")
return
deleted_count = 0
for nb in to_delete:
if notebookutils.notebook.delete(nb.displayName):
deleted_count += 1
print(f"Deleted: {nb.displayName}")
else:
print(f"Failed to delete: {nb.displayName}")
print(f"\nDeleted {deleted_count} of {len(to_delete)} notebooks")
# Always run with dry_run=True first to preview
cleanup_notebooks("temp_", dry_run=True)
Tip
Untuk penghapusan massal yang aman, selalu jalankan dengan dry_run=True terlebih dahulu untuk mempratinjau buku catatan mana yang akan dihapus. Pertimbangkan untuk mengganti nama buku catatan dengan _TO_DELETE awalan alih-alih menghapusnya segera, sehingga Anda dapat memulihkannya jika diperlukan.
Daftar buku catatan
Gunakan notebookutils.notebook.list() untuk menghitung buku catatan di ruang kerja. Ini mengembalikan array Artifact objek.
Parameter-parameternya
| Parameter | Tipe | Required | Deskripsi |
|---|---|---|---|
workspaceId |
string | No | ID Ruang Kerja. Biarkan kosong untuk ruang kerja saat ini. |
maxResults |
Integer | No | Jumlah maksimum hasil yang akan dikembalikan. Setelan awal menjadi 1000. |
Mencantumkan semua buku catatan di ruang kerja saat ini
notebooks = notebookutils.notebook.list()
print(f"Found {len(notebooks)} notebooks:")
for nb in notebooks:
print(f" - {nb.displayName} (ID: {nb.id})")
Mencantumkan buku catatan di ruang kerja lain
workspace_id = "cccccccc-3333-4444-5555-dddddddddddd"
notebooks = notebookutils.notebook.list(workspaceId=workspace_id)
print(f"Found {len(notebooks)} notebooks in workspace {workspace_id}")
Mengembalikan nilai
Metode list() mengembalikan array dari objek Artifact. Setiap objek berisi displayNameproperti , id, dan description .
Memfilter buku catatan menurut pola nama
all_notebooks = notebookutils.notebook.list()
# Filter for notebooks that start with a specific prefix
processing_notebooks = [nb for nb in all_notebooks if nb.displayName.startswith("Process_")]
print(f"Found {len(processing_notebooks)} processing notebooks:")
for nb in processing_notebooks:
print(f" - {nb.displayName}")
Mengkloning buku catatan
Gunakan list() dan getDefinition() bersama-sama untuk mengkloning buku catatan dalam ruang kerja yang sama atau ke ruang kerja lain.
def clone_notebook(source_name, target_name, target_workspace=""):
"""Clone a notebook by retrieving its content and creating a copy."""
source = notebookutils.notebook.get(source_name)
content = notebookutils.notebook.getDefinition(source_name)
cloned = notebookutils.notebook.create(
name=target_name,
description=f"Clone of {source_name}",
content=content,
workspaceId=target_workspace
)
print(f"Cloned {source_name} to {cloned.displayName}")
return cloned
cloned_notebook = clone_notebook("TemplateNotebook", "NewInstance")
Memigrasikan buku catatan ke ruang kerja lain
def migrate_notebook(name, target_workspace_id, new_name=None):
"""Migrate a notebook from the current workspace to another workspace."""
content = notebookutils.notebook.getDefinition(name)
target_name = new_name if new_name else name
migrated = notebookutils.notebook.create(
name=target_name,
description=f"Migrated from {name}",
content=content,
workspaceId=target_workspace_id
)
print(f"Migrated {name} to workspace {target_workspace_id} as {target_name}")
return migrated
target_ws = "dddddddd-4444-5555-6666-eeeeeeeeeeee"
migrated_nb = migrate_notebook("DataPipeline", target_ws, "DataPipeline_v2")