Databricks アプリケーション(Databricks が提供するアプリ構築プラットフォーム)用の Python バックエンド(サーバー側の処理)— FastAPI(デフォルト)、Flask、Dash、Streamlit、Gradio、Reflex に対応しています。 **新しい Databricks アプリケーションのデフォルトは `databricks-apps`(AppKit — Node/TypeScript/React)です。まずはこちらを優先してください。** このスキルは、以下の場合にのみ使用してください: - ユーザーが Python バックエンドを明確に指定している - 既存の Python アプリを拡張する必要がある - チーム全体が Python のみを使用している カバー範囲: - OAuth 認証(ユーザーの本人確認) - アプリケーションリソース - SQL ウェアハウス(データベース)および Lakebase(データ管理基盤)への接続 - 基盤モデル(大規模言語モデル)、ベクトル検索(テキスト検索機能)、モデル提供 API(`databricks-python-sdk` 経由) - CLI またはDAB(Databricks Asset Bundles — リソース定義セット)を使ったデプロイ(公開・配置)
Python backend for Databricks Apps — FastAPI (default), Flask, Dash, Streamlit, Gradio, Reflex. **Default for a new Databricks App is `databricks-apps` (AppKit — Node/TypeScript/React) — reach for it first.** Use this skill only when the user asks for a Python backend, extends an existing Python app, or the team is Python-only. Covers OAuth auth, app resources, SQL warehouse and Lakebase connectivity, foundation-model / Vector Search / model-serving APIs (via `databricks-python-sdk`), and deployment via CLI or DABs.
まず、このスキルが適切かどうか確認してください。 Databricks Apps の標準設定は databricks-apps です(AppKit — Node.js + TypeScript + React SDK)。ユーザーが明確に Python バックエンドを希望していない、既存の Python アプリを拡張していない、またはチームが Python のみの場合を除き、まずそのスキルをロードしてください。以下は Python バックエンドの代替案です。
Config() を使う(トークンをコード内に書き込まない)app.yaml の valueFrom を使う(リソース ID をコード内に書き込まない)dash-bootstrap-components を使う@st.cache_resource を使うこのチェックリストをコピーし、各項目を確認してください:
- [ ] フレームワークを選択した
- [ ] 認証戦略を決定: アプリ認証、ユーザー認証、または両方
- [ ] アプリリソースを特定: SQL ウェアハウス、Lakebase、提供エンドポイントなど
- [ ] バックエンド データ戦略を決定: SQL ウェアハウス、Lakebase、または SDK
- [ ] デプロイ方法を選択: CLI または DABs
| フレームワーク | 最適な用途 | app.yaml コマンド |
|---|---|---|
| FastAPI(デフォルト) | Python バックエンドの標準選択 — 非同期 API、自動生成される OpenAPI ドキュメント、JSON を返すアプリ | ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"] |
| Flask | カスタム REST API、軽量アプリ、ウェブフック | ["gunicorn", "app:app", "-w", "4", "-b", "0.0.0.0:8000"] |
| Dash | 本番用ダッシュボード、BI ツール、複雑なインタラクション | ["python", "app.py"] |
| Streamlit | 迅速なプロトタイピング、データサイエンスアプリ、UI が Python ウィジェットの並びである内部向けツール | ["streamlit", "run", "app.py"] |
| Gradio | ML デモ、モデルインターフェース、チャット UI | ["python", "app.py"] |
| Reflex | JavaScript 不要なフルスタック Python アプリ | ["reflex", "run", "--env", "prod"] |
デフォルト: FastAPI。 ユーザーが Streamlit スタイルのウィジェットプロトタイピング(Streamlit)、重たいダッシュボードグリッド(Dash)、または Gradio スタイルの ML デモを明確に要望していない限り、FastAPI を選びます。FastAPI は JS/HTML フロントエンドまたは JSON を処理する呼び出し側と自然に組み合わせでき、Node 側で databricks-apps が採用する姿勢と同じです。
| 概念 | 詳細 |
|---|---|
| ランタイム | Python 3.11、Ubuntu 22.04、2 vCPU、6 GB RAM |
| プリインストール済み | Dash 2.18.1、Streamlit 1.38.0、Gradio 4.44.0、Flask 3.0.3、FastAPI 0.115.0 |
| 認証(アプリ) | Config() 経由のサービスプリンシパル — 自動注入される DATABRICKS_CLIENT_ID / DATABRICKS_CLIENT_SECRET |
| 認証(ユーザー) | x-forwarded-access-token ヘッダー — references/1-authorization.md を参照 |
| リソース | app.yaml の valueFrom — references/2-app-resources.md を参照 |
| SDK / Foundation Models / Vector Search / Model Serving | databricks-python-sdk スキルを使う — 同じ WorkspaceClient と OpenAI 互換の基盤モデルパターンが Databricks App 内で機能 |
| ドキュメント | https://docs.databricks.com/dev-tools/databricks-apps/ |
認証: アプリ認証またはユーザー認証を設定する際は references/1-authorization.md を使用 — サービスプリンシパル認証、代理ユーザートークン、OAuth スコープ、フレームワーク別コード例をカバー (キーワード: OAuth、サービスプリンシパル、ユーザー認証、代理、アクセストークン、スコープ)
アプリリソース: アプリを Databricks リソースに接続する際は references/2-app-resources.md を使用 — SQL ウェアハウス、Lakebase、モデル提供、シークレット、ボリューム、valueFrom パターンをカバー
(キーワード: リソース、valueFrom、SQL ウェアハウス、モデル提供、シークレット、ボリューム、接続)
フレームワーク: フレームワーク別の Databricks 固有パターンは references/3-frameworks.md を参照 — FastAPI(デフォルト)、Flask、Dash、Streamlit、Gradio、Reflex — 認証統合とデプロイコマンド付き (キーワード: FastAPI、Flask、Dash、Streamlit、Gradio、Reflex、フレームワーク選択)
デプロイ: アプリをデプロイする際は references/4-deployment.md を使用 — Databricks CLI、Asset Bundles(DABs)、app.yaml 設定、デプロイ後の確認をカバー (キーワード: デプロイ、CLI、DABs、アセットバンドル、app.yaml、ログ)
Lakebase: Lakebase(PostgreSQL)をアプリのデータレイヤーとして使う際は references/5-lakebase.md を使用 — 自動注入される環境変数、psycopg2 / asyncpg パターン、Lakebase と SQL ウェアハウスの選択基準をカバー (キーワード: Lakebase、PostgreSQL、psycopg2、asyncpg、トランザクション、PGHOST)
CLI コマンド: CLI 経由でアプリライフサイクル(作成、デプロイ、監視、削除)を管理する際は references/6-cli-approach.md を参照 (キーワード: CLI、アプリ作成、アプリデプロイ、アプリログ)
Foundation Models / SDK / Vector Search / Model Serving: OpenAI 互換の基盤モデルクライアント、WorkspaceClient の呼び出し、Vector Search、モデル提供の実行には databricks-python-sdk スキルを使う — 同じパターンが Databricks App 内で機能します。このスキルの examples/ フォルダ(fm-minimal-chat.py、fm-parallel-calls.py、fm-structured-outputs.py、llm_config.py)は App 側の配線のみを示しています。
タスクの種類を判断:
まったく新しいアプリ? → databricks-apps をまずロード(AppKit / Node)。ユーザーが Python バックエンドを明確に要望した場合のみこのスキルに留まる
Python バックエンド確認済み? → Python フレームワークの選択 — デフォルトは FastAPI
認証を設定中? → references/1-authorization.md を読む
データ/リソースに接続中? → references/2-app-resources.md を読む
Lakebase(PostgreSQL)を使用中? → references/5-lakebase.md を読む
Databricks にデプロイ中? → references/4-deployment.md を読む
CLI でアプリライフサイクルを管理中? → references/6-cli-approach.md を読む
Foundation Model / LLM API、Vector Search、またはモデル提供エンドポイントを呼び出し中? → databricks-python-sdk スキルをロード。このスキルの examples/ フォルダはそれらの SDK パターン上の App 側の配線のみを示します。
該当するガイドの指示に従う。
すべての Python Databricks アプリはこのパターンに従います:
app-directory/
├── app.py # メインアプリケーション(またはフレームワーク固有の名前)
├── models.py # Pydantic データモデル
├── backend.py # データアクセスレイヤー
├── requirements.txt # 追加の Python 依存関係
├── app.yaml # Databricks Apps 設定
└── README.md
import os
from databricks.sdk.core import Config
USE_MOCK = os.getenv("USE_MOCK_BACKEND", "true").lower() == "true"
if USE_MOCK:
from backend_mock import MockBackend as Backend
else:
from backend_real import RealBackend as Backend
backend = Backend()
from databricks.sdk.core import Config
from databricks import sql
cfg = Config() # 環境から認証情報を自動検出
conn = sql.connect(
server_hostname=cfg.host,
http_path=f"/sql/1.0/warehouses/{os.getenv('DATABRICKS_WAREHOUSE_ID')}",
credentials_provider=lambda: cfg.authenticate,
)
from pydantic import BaseModel, Field
from datetime import datetime
from enum import Enum
class Status(str, Enum):
ACTIVE = "active"
PENDING = "pending"
class EntityOut(BaseModel):
id: str
name: str
status: Status
created_at: datetime
class EntityIn(BaseModel):
name: str = Field(..., min_length=1)
status: Status = Status.PENDING
| 問題 | 解決策 |
|---|---|
| 接続枯渇 | @st.cache_resource(Streamlit)またはコネクションプール使用 |
| 認証トークンが見つからない | x-forwarded-access-token ヘッダーを確認 — デプロイ時のみ利用可能、ローカルでは不可 |
| アプリが起動しない | app.yaml コマンドがフレームワークと一致するか確認、databricks apps logs <name> で確認 |
| リソースにアクセスできない | UI でリソースを追加、サービスプリンシパルがパーミッションを持つか確認、app.yaml で valueFrom を使用 |
| デプロイ時にインポートエラー | 不足しているパッケージを requirements.txt に追加(プリインストール済みパッケージはリスト不要) |
| Lakebase アプリ起動時にクラッシュ | psycopg2 / asyncpg はプリインストールされていない — requirements.txt に追加必須 |
| ポート競合 | アプリは DATABRICKS_APP_PORT 環境変数にバインド(デフォルト 8000)。8080 は使用禁止。Streamlit は自動設定;その他はコード内で環境変数を読むか app.yaml コマンドで 8000 を使用 |
| Streamlit: set_page_config エラー | st.set_page_config() は Streamlit コマンドの最初に配置必須 |
| Dash: スタイルが適用されていない | dash-bootstrap-components を追加、dbc.themes.BOOTSTRAP を使用 |
| クエリが遅い | トランザクション/低遅延は Lakebase、分析クエリは SQL ウェアハウスを使用 |
| 制約 | 詳細 |
|---|---|
| ランタイム | Python 3.11、Ubuntu 22.04 LTS |
| コンピュート | 2 vCPU、6 GB メモリ(デフォルト) |
| プリインストール済みフレームワーク | Dash、Streamlit、Gradio、Flask、FastAPI、 |
First, confirm this skill is the right one. The default for new Databricks Apps is databricks-apps (AppKit — Node.js + TypeScript + React SDK). Load that skill first unless the user explicitly asks for a Python backend, is extending an existing Python app, or the team is Python-only. Everything below is the Python-backend alternative.
Config() for authentication (never hardcode tokens)app.yaml valueFrom for resources (never hardcode resource IDs)dash-bootstrap-components for Dash app layout and styling@st.cache_resource for Streamlit database connectionsCopy this checklist and verify each item:
- [ ] Framework selected
- [ ] Auth strategy decided: app auth, user auth, or both
- [ ] App resources identified (SQL warehouse, Lakebase, serving endpoint, etc.)
- [ ] Backend data strategy decided (SQL warehouse, Lakebase, or SDK)
- [ ] Deployment method: CLI or DABs
| Framework | Best For | app.yaml Command |
|---|---|---|
| FastAPI (default) | Any Python backend by default — async APIs, auto-generated OpenAPI docs, JSON-serving apps | ["uvicorn", "app:app", "--host", "0.0.0.0", "--port", "8000"] |
| Flask | Custom REST APIs, lightweight apps, webhooks | ["gunicorn", "app:app", "-w", "4", "-b", "0.0.0.0:8000"] |
| Dash | Production dashboards, BI tools, complex interactivity | ["python", "app.py"] |
| Streamlit | Rapid prototyping, data science apps, internal tools where the UI is a series of Python widgets | ["streamlit", "run", "app.py"] |
| Gradio | ML demos, model interfaces, chat UIs | ["python", "app.py"] |
| Reflex | Full-stack Python apps without JavaScript | ["reflex", "run", "--env", "prod"] |
Default: FastAPI. Reach for FastAPI unless the user explicitly asks for Streamlit-style widget prototyping (Streamlit), a heavy dashboard grid (Dash), or a Gradio-style ML demo. FastAPI pairs naturally with a JS/HTML frontend or a JSON-consuming caller — the same posture databricks-apps uses on the Node side.
| Concept | Details |
|---|---|
| Runtime | Python 3.11, Ubuntu 22.04, 2 vCPU, 6 GB RAM |
| Pre-installed | Dash 2.18.1, Streamlit 1.38.0, Gradio 4.44.0, Flask 3.0.3, FastAPI 0.115.0 |
| Auth (app) | Service principal via Config() — auto-injected DATABRICKS_CLIENT_ID/DATABRICKS_CLIENT_SECRET |
| Auth (user) | x-forwarded-access-token header — see references/1-authorization.md |
| Resources | valueFrom in app.yaml — see references/2-app-resources.md |
| SDK / Foundation Models / Vector Search / Model Serving | Use the databricks-python-sdk skill — same WorkspaceClient and OpenAI-compatible foundation-model patterns work inside a Databricks App |
| Docs | https://docs.databricks.com/dev-tools/databricks-apps/ |
Authorization: Use references/1-authorization.md when configuring app or user authorization — covers service principal auth, on-behalf-of user tokens, OAuth scopes, and per-framework code examples. (Keywords: OAuth, service principal, user auth, on-behalf-of, access token, scopes)
App resources: Use references/2-app-resources.md when connecting your app to Databricks resources — covers SQL warehouses, Lakebase, model serving, secrets, volumes, and the valueFrom pattern. (Keywords: resources, valueFrom, SQL warehouse, model serving, secrets, volumes, connections)
Frameworks: See references/3-frameworks.md for Databricks-specific patterns per framework — FastAPI (default), Flask, Dash, Streamlit, Gradio, Reflex — with auth integration and deployment commands. (Keywords: FastAPI, Flask, Dash, Streamlit, Gradio, Reflex, framework selection)
Deployment: Use references/4-deployment.md when deploying your app — covers Databricks CLI, Asset Bundles (DABs), app.yaml configuration, and post-deployment verification. (Keywords: deploy, CLI, DABs, asset bundles, app.yaml, logs)
Lakebase: Use references/5-lakebase.md when using Lakebase (PostgreSQL) as your app's data layer — covers auto-injected env vars, psycopg2/asyncpg patterns, and when to choose Lakebase vs SQL warehouse. (Keywords: Lakebase, PostgreSQL, psycopg2, asyncpg, transactional, PGHOST)
CLI commands: Use references/6-cli-approach.md for managing app lifecycle via CLI — covers creating, deploying, monitoring, and deleting apps. (Keywords: CLI, create app, deploy app, app logs)
Foundation Models / SDK / Vector Search / Model Serving: Use the databricks-python-sdk skill for the OpenAI-compatible foundation-model client, WorkspaceClient calls, Vector Search, and model-serving invocation — the same patterns apply inside a Databricks App. The examples in this skill's examples/ folder (fm-minimal-chat.py, fm-parallel-calls.py, fm-structured-outputs.py, llm_config.py) show the App-side wiring only.
Determine the task type:
New app from scratch? → Load databricks-apps first (AppKit / Node). Only stay in this skill if the user explicitly asks for a Python backend.
Python-backend confirmed? → Python Framework Selection — default to FastAPI.
Setting up authorization? → Read references/1-authorization.md
Connecting to data/resources? → Read references/2-app-resources.md
Using Lakebase (PostgreSQL)? → Read references/5-lakebase.md
Deploying to Databricks? → Read references/4-deployment.md
Using CLI for app lifecycle? → Read references/6-cli-approach.md
Calling foundation model / LLM APIs, Vector Search, or model-serving endpoints? → Load the databricks-python-sdk skill. This skill's examples/ folder shows only the App-side wiring on top of those SDK patterns.
Follow the instructions in the relevant guide.
All Python Databricks apps follow this pattern:
app-directory/
├── app.py # Main application (or framework-specific name)
├── models.py # Pydantic data models
├── backend.py # Data access layer
├── requirements.txt # Additional Python dependencies
├── app.yaml # Databricks Apps configuration
└── README.md
import os
from databricks.sdk.core import Config
USE_MOCK = os.getenv("USE_MOCK_BACKEND", "true").lower() == "true"
if USE_MOCK:
from backend_mock import MockBackend as Backend
else:
from backend_real import RealBackend as Backend
backend = Backend()
from databricks.sdk.core import Config
from databricks import sql
cfg = Config() # Auto-detects credentials from environment
conn = sql.connect(
server_hostname=cfg.host,
http_path=f"/sql/1.0/warehouses/{os.getenv('DATABRICKS_WAREHOUSE_ID')}",
credentials_provider=lambda: cfg.authenticate,
)
from pydantic import BaseModel, Field
from datetime import datetime
from enum import Enum
class Status(str, Enum):
ACTIVE = "active"
PENDING = "pending"
class EntityOut(BaseModel):
id: str
name: str
status: Status
created_at: datetime
class EntityIn(BaseModel):
name: str = Field(..., min_length=1)
status: Status = Status.PENDING
| Issue | Solution |
|---|---|
| Connection exhausted | Use @st.cache_resource (Streamlit) or connection pooling |
| Auth token not found | Check x-forwarded-access-token header — only available when deployed, not locally |
| App won't start | Check app.yaml command matches framework; check databricks apps logs <name> |
| Resource not accessible | Add resource via UI, verify SP has permissions, use valueFrom in app.yaml |
| Import error on deploy | Add missing packages to requirements.txt (pre-installed packages don't need listing) |
| Lakebase app crashes on start | psycopg2/asyncpg are NOT pre-installed — MUST add to requirements.txt |
| Port conflict | Apps must bind to DATABRICKS_APP_PORT env var (defaults to 8000). Never use 8080. Streamlit is auto-configured; for others, read the env var in code or use 8000 in app.yaml command |
| Streamlit: set_page_config error | st.set_page_config() must be the first Streamlit command |
| Dash: unstyled layout | Add dash-bootstrap-components; use dbc.themes.BOOTSTRAP |
| Slow queries | Use Lakebase for transactional/low-latency; SQL warehouse for analytical queries |
| Constraint | Details |
|---|---|
| Runtime | Python 3.11, Ubuntu 22.04 LTS |
| Compute | 2 vCPUs, 6 GB memory (default) |
| Pre-installed frameworks | Dash, Streamlit, Gradio, Flask, FastAPI, Shiny |
| Custom packages | Add to requirements.txt in app root |
| Network | Apps can reach Databricks APIs; external access depends on workspace config |
| User auth | Public Preview — workspace admin must enable before adding scopes |
WorkspaceClient, OpenAI-compatible foundation-model client, Vector Search, model-serving invocation; the same patterns work inside a Databricks App原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。