Tutoriel : Développer une application Databricks avec Streamlit

Ce tutoriel montre comment créer une application Databricks à l’aide du connecteur SQL Databricks pour Python et Streamlit. Vous allez apprendre à développer une application qui effectue les opérations suivantes :

  • Lit une table de catalogue Unity et l’affiche dans une interface Streamlit.
  • Modifie les données et les réinscrit dans la table.

Étape 1 : Configurer les privilèges

Ces exemples supposent que votre application utilise l’autorisation d’application. Le principal de service de votre application doit avoir :

  • Privilège SELECT sur la table Unity Catalog
  • Privilège MODIFY sur la table Unity Catalog
  • Privilège CAN USE sur l’entrepôt SQL

Pour plus d’informations, consultez référence des privilèges de Unity Catalog et les listes de contrôle d’accès SQL Warehouse.

Étape 2 : Installer les dépendances

Créez un requirements.txt fichier et incluez les packages suivants :

databricks-sdk
databricks-sql-connector
streamlit
pandas

Étape 3 : Configurer l’exécution de l’application

Créez un app.yaml fichier pour définir le démarrage de votre application dans Azure Databricks Apps.

command: ['streamlit', 'run', 'app.py']

Étape 4 : Lire une table de catalogue Unity

Cet exemple de code montre comment lire des données à partir d’une table De catalogue Unity et l’afficher à l’aide de Streamlit. Créez un app.py fichier qui répond aux objectifs suivants :

  • Utilise l’authentification du principal app service.
  • Invite l’utilisateur à entrer le chemin HTTP de l’entrepôt SQL et le nom de la table catalogue Unity.
  • Exécute une SELECT * requête sur la table spécifiée.
  • Affiche le résultat dans un Streamlit st.dataframe.

app.py

import pandas as pd
import streamlit as st
from databricks import sql
from databricks.sdk.core import Config
import os

cfg = Config()

# Use app service principal authentication
def get_connection(http_path):
    server_hostname = cfg.host
    if server_hostname.startswith('https://'):
        server_hostname = server_hostname.replace('https://', '')
    elif server_hostname.startswith('http://'):
        server_hostname = server_hostname.replace('http://', '')
    return sql.connect(
        server_hostname=server_hostname,
        http_path=http_path,
        credentials_provider=lambda: cfg.authenticate,
        _use_arrow_native_complex_types=False,
    )

# Read data from a Unity Catalog table and return it as a pandas DataFrame
def read_table(table_name: str, conn) -> pd.DataFrame:
    with conn.cursor() as cursor:
        cursor.execute(f"SELECT * FROM {table_name}")
        return cursor.fetchall_arrow().to_pandas()

# Use Streamlit input fields to accept user input
http_path_input = st.text_input(
    "Enter your Databricks HTTP Path:", placeholder="/sql/1.0/warehouses/xxxxxx"
)
table_name = st.text_input(
    "Specify a Unity Catalog table name:", placeholder="catalog.schema.table"
)

# Display the result in a Streamlit DataFrame
if http_path_input and table_name:
    conn = get_connection(http_path_input)
    df = read_table(table_name, conn)
    st.dataframe(df)
else:
    st.warning("Provide both the warehouse path and a table name to load data.")

Étape 5 : Modifier une table de catalogue Unity

Cet exemple de code permet aux utilisateurs de lire, de modifier et d’écrire des modifications dans une table de catalogue Unity à l’aide des fonctionnalités de modification des données de Streamlit. Ajoutez les fonctionnalités suivantes au app.py fichier :

  • Utilisez INSERT OVERWRITE pour écrire les données mises à jour dans la table.

app.py

import pandas as pd
import streamlit as st
from databricks import sql
from databricks.sdk.core import Config
import math

cfg = Config()

# Use app service principal authentication
def get_connection(http_path):
    server_hostname = cfg.host
    if server_hostname.startswith('https://'):
        server_hostname = server_hostname.replace('https://', '')
    elif server_hostname.startswith('http://'):
        server_hostname = server_hostname.replace('http://', '')
    return sql.connect(
        server_hostname=server_hostname,
        http_path=http_path,
        credentials_provider=lambda: cfg.authenticate,
        _use_arrow_native_complex_types=False,
    )

# Read data from a Unity Catalog table and return it as a pandas DataFrame
def read_table(table_name: str, conn) -> pd.DataFrame:
    with conn.cursor() as cursor:
        cursor.execute(f"SELECT * FROM {table_name}")
        return cursor.fetchall_arrow().to_pandas()

# Format values for SQL, handling NaN/None as NULL
def format_value(val):
    if val is None or (isinstance(val, float) and math.isnan(val)):
        return 'NULL'
    else:
        return repr(val)

# Use `INSERT OVERWRITE` to update existing rows and insert new ones
def insert_overwrite_table(table_name: str, df: pd.DataFrame, conn):
    progress = st.empty()
    with conn.cursor() as cursor:
        rows = list(df.itertuples(index=False))
        values = ",".join([f"({','.join(map(format_value, row))})" for row in rows])
        with progress:
            st.info("Calling Databricks SQL...")
        cursor.execute(f"INSERT OVERWRITE {table_name} VALUES {values}")
    progress.empty()
    st.success("Changes saved")

# Use Streamlit input fields to accept user input
http_path_input = st.text_input(
    "Enter your Databricks HTTP Path:", placeholder="/sql/1.0/warehouses/xxxxxx"
)
table_name = st.text_input(
    "Specify a Unity Catalog table name:", placeholder="catalog.schema.table"
)

# Display the result in a Streamlit DataFrame
if http_path_input and table_name:
    conn = get_connection(http_path_input)
    if conn:
        st.success("✅ Connected successfully!")
        original_df = read_table(table_name, conn)
        edited_df = st.data_editor(original_df, num_rows="dynamic", hide_index=True)
        df_diff = pd.concat([original_df, edited_df]).drop_duplicates(keep=False)
        if not df_diff.empty:
            st.warning(f"⚠️ You have {len(df_diff) // 2} unsaved changes")
            if st.button("Save changes"):
                insert_overwrite_table(table_name, edited_df, conn)
                st.rerun()
else:
    st.warning("Provide both the warehouse path and a table name to load data.")

Étapes suivantes