Token导航 LogoToken导航TokenDH.com
开发需要联网github未标认证来源可访问许可证需确认审计通过

databricks-sdk-patternsdatabricks SDK 模式

Agent Skill

用于辅助数据整理、表格处理、CSV/Excel 分析、指标计算和图表准备。它适合让 Agent 清洗字段、汇总数据、发现异常、生成统计口径或把分析结果转成可读说明。使用时需要确认数据来源、字段含义和时间范围,避免把样本数据当全量事实;涉及敏感数据、导出文件或批量写回时,应先确认权限和脱敏边界。

总安装

629

周安装

27

GitHub Stars

2,112

下载量

220
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

2

许可证

unknown

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:databricks-sdk-patterns(databricks SDK 模式)
来源仓库:https://github.com/jeremylongshore/claude-code-plugins-plus-skills
仓库路径:skills/databricks-sdk-patterns
安装命令:
npx skills add https://github.com/jeremylongshore/claude-code-plugins-plus-skills --skill databricks-sdk-patterns
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。该命令会通过 npx skills 从第三方来源获取 Skill;本站只展示命令,不托管安装包,也不自动执行。

skills.shnpx skills
npx skills add https://github.com/jeremylongshore/claude-code-plugins-plus-skills --skill databricks-sdk-patterns

简介

展示 Databricks Python SDK 在生产环境中的最佳实践模式。

  • 包括单例客户端、错误处理、资源生命周期管理与类型安全作业构建。
  • 适用于构建健壮、可维护的自动化脚本与长期运行服务。
  • 需安装 databricks-sdk v0.20+,并优先复用上下文管理器减少资源开销。
  • 适用宿主包括 Codex、Claude、Cursor、Gemini CLI,接入前应确认版本、权限和运行环境要求。

SKILL.md

Databricks SDK Patterns

Overview

Production-ready patterns for the Databricks Python SDK (databricks-sdk). These patterns cover client initialization, error handling, resource lifecycle management, and type-safe job construction.

Prerequisites

  • Completed databricks-install-auth setup
  • databricks-sdk v0.20+ installed (pip install databricks-sdk)
  • Understanding of Python context managers and dataclasses

Instructions

Step 1: Implement Singleton Client

Avoid creating multiple WorkspaceClient instances. Each one re-authenticates and holds its own HTTP session.

from databricks.sdk import WorkspaceClient
from functools import lru_cache

@lru_cache(maxsize=1)
def get_workspace_client(profile: str = "DEFAULT") -> WorkspaceClient:
    """Return a singleton WorkspaceClient, cached per profile."""
    return WorkspaceClient(profile=profile)

# Usage throughout your codebase
w = get_workspace_client()
w_prod = get_workspace_client(profile="production")

For multi-workspace scripts, use AccountClient at the account level:

from databricks.sdk import AccountClient

a = AccountClient(
    host="https://accounts.cloud.databricks.com",
    account_id="your-account-id",
)
for workspace in a.workspaces.list():
    print(f"{workspace.workspace_name}: {workspace.deployment_name}")

Step 2: Add Error Handling Wrapper

Wrap API calls with structured error handling that distinguishes transient from permanent failures.

from dataclasses import dataclass
from typing import TypeVar, Generic, Optional
from databricks.sdk.errors import (
    NotFound,
    PermissionDenied,
    TooManyRequests,
    TemporarilyUnavailable,
    ResourceConflict,
)

T = TypeVar("T")

@dataclass
class Result(Generic[T]):
    value: Optional[T] = None
    error: Optional[str] = None
    retryable: bool = False

    @property
    def ok(self) -> bool:
        return self.error is None

def safe_api_call(func, *args, **kwargs) -> Result:
    """Execute a Databricks API call with structured error handling."""
    try:
        return Result(value=func(*args, **kwargs))
    except NotFound as e:
        return Result(error=f"Not found: {e.message}", retryable=False)
    except PermissionDenied as e:
        return Result(error=f"Permission denied: {e.message}", retryable=False)
    except TooManyRequests as e:
        return Result(error=f"Rate limited (retry after {e.retry_after_secs}s)", retryable=True)
    except TemporarilyUnavailable as e:
        return Result(error=f"Service unavailable: {e.message}", retryable=True)
    except ResourceConflict as e:
        return Result(error=f"Conflict: {e.message}", retryable=False)

# Usage
result = safe_api_call(w.clusters.get, cluster_id="abc-123")
if result.ok:
    print(f"Cluster state: {result.value.state}")
elif result.retryable:
    print(f"Transient error, retry: {result.error}")
else:
    print(f"Permanent failure: {result.error}")

Step 3: Context Manager for Cluster Lifecycle

Ensure clusters are cleaned up after use, even on exceptions.

from contextlib import contextmanager
from databricks.sdk import WorkspaceClient
from databricks.sdk.service.compute import ClusterDetails, State

@contextmanager
def managed_cluster(w: WorkspaceClient, cluster_config: dict):
    """Start a cluster, yield it, and terminate on exit."""
    cluster = w.clusters.create_and_wait(**cluster_config)
    try:
        yield cluster
    finally:
        if cluster.state in (State.RUNNING, State.PENDING, State.RESIZING):
            w.clusters.delete(cluster_id=cluster.cluster_id)
            print(f"Terminated cluster {cluster.cluster_id}")

# Usage
config = {
    "cluster_name": "ephemeral-etl",
    "spark_version": "14.3.x-scala2.12",
    "node_type_id": "i3.xlarge",
    "num_workers": 2,
    "autotermination_minutes": 30,
}

with managed_cluster(w, config) as cluster:
    print(f"Running on cluster {cluster.cluster_id}")
    # Do work...
    w.jobs.run_now(job_id=123)
# Cluster is auto-terminated here

Step 4: Type-Safe Job Builder

Use the SDK's dataclass types instead of raw dicts for job configuration. This catches schema errors at construction time.

from databricks.sdk.service.jobs import (
    CreateJob,
    JobCluster,
    Task,
    NotebookTask,
    CronSchedule,
    JobEmailNotifications,
)
from databricks.sdk.service.compute import ClusterSpec, AutoScale

def build_etl_job(name: str, notebook_path: str, schedule_cron: str) -> CreateJob:
    """Build a fully-typed ETL job configuration."""
    return CreateJob(
        name=name,
        job_clusters=[
            JobCluster(
                job_cluster_key="etl_cluster",
                new_cluster=ClusterSpec(
                    spark_version="14.3.x-scala2.12",
                    node_type_id="i3.xlarge",
                    autoscale=AutoScale(min_workers=1, max_workers=4),
                ),
            )
        ],
        tasks=[
            Task(
                task_key="main",
                job_cluster_key="etl_cluster",
                notebook_task=NotebookTask(notebook_path=notebook_path),
            )
        ],
        schedule=CronSchedule(
            quartz_cron_expression=schedule_cron,
            timezone_id="UTC",
        ),
        email_notifications=JobEmailNotifications(
            on_failure=["oncall@company.com"],
        ),
    )

# Create the job
job_config = build_etl_job(
    name="daily-sales-etl",
    notebook_path="/Repos/team/etl/sales_pipeline",
    schedule_cron="0 0 6 * * ?",
)
created = w.jobs.create(**job_config.as_dict())
print(f"Created job {created.job_id}")

Step 5: Pagination Helper

The SDK paginates list results automatically via iterators, but when you need all results at once or want progress tracking:

from typing import Callable, Iterator

def collect_with_progress(iterator: Iterator, label: str, batch_size: int = 100) -> list:
    """Collect paginated results with progress logging."""
    items = []
    for i, item in enumerate(iterator, 1):
        items.append(item)
        if i % batch_size == 0:
            print(f"  {label}: fetched {i} items...")
    print(f"  {label}: {len(items)} total")
    return items

# Usage
all_jobs = collect_with_progress(w.jobs.list(), "Jobs")
all_clusters = collect_with_progress(w.clusters.list(), "Clusters")
running = [c for c in all_clusters if c.state == State.RUNNING]
print(f"Running clusters: {len(running)}/{len(all_clusters)}")

Output

  • Singleton WorkspaceClient with profile-based caching
  • Result wrapper for type-safe, structured error handling
  • Context manager for auto-terminating ephemeral clusters
  • Type-safe job builder using SDK dataclasses (no raw dicts)
  • Pagination helper with progress logging

Error Handling

ErrorCauseSolution
databricks.sdk.errors.NotFoundResource deleted or wrong IDValidate IDs before use; handle gracefully in cleanup
databricks.sdk.errors.PermissionDeniedToken lacks required scopeUse service principal with correct Unity Catalog grants
databricks.sdk.errors.InvalidParameterValueWrong type in job configUse SDK dataclasses instead of raw dicts for compile-time safety
databricks.sdk.errors.ResourceAlreadyExistsDuplicate cluster/job nameAdd unique suffix or check-before-create pattern
AttributeError on SDK objectsSDK version mismatchPin databricks-sdk>=0.20.0 in requirements.txt

Examples

Health Check Script

w = get_workspace_client()
me = w.current_user.me()
print(f"Authenticated as: {me.user_name}")
print(f"Workspace: {w.config.host}")
print(f"Active clusters: {sum(1 for c in w.clusters.list() if c.state == State.RUNNING)}")
print(f"Jobs defined: {sum(1 for _ in w.jobs.list())}")

Multi-Workspace Inventory

a = AccountClient()
for ws in a.workspaces.list():
    w = WorkspaceClient(host=f"https://{ws.deployment_name}.cloud.databricks.com")
    clusters = list(w.clusters.list())
    running = [c for c in clusters if c.state == State.RUNNING]
    print(f"{ws.workspace_name}: {len(running)} running / {len(clusters)} total clusters")

Resources

Next Steps

Apply patterns in databricks-core-workflow-a for Delta Lake ETL.

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Codex

38.14%
按下载量换算84

Claude

30.76%
按下载量换算68

Cursor

17.58%
按下载量换算39

Gemini CLI

8.64%
按下载量换算19

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。当前只有一个来源,正式发布前建议补源仓库或其他目录站核验。

来源信息

继续浏览同类 Skills