Developer docs / AI Fabric tutorials

Publish explorable data with Datasette

  • Volume
  • Web endpoint
  • Image DSL

Take it for a spin

The whole program in one file, ready to run.

datasette_publish.py
import bladekit

app = bladekit.app("datasette-publish")

# The demo database lives on a Volume so it survives redeploys and is populated
# exactly once: the first replica to boot builds it, then commits it back as a
# new generation for later replicas to reuse.
db_vol = bladekit.Volume.from_name("datasette-db", create_if_missing=True)

image = (
    bladekit.Image.debian_slim(python_version="3.12")
    .pip_install("datasette", "sqlite-utils")
)


def _ensure_db(path: str) -> None:
    """Create and populate the sample SQLite database if it is not there yet."""
    import os

    if os.path.exists(path):
        return
    import sqlite_utils

    db = sqlite_utils.Database(path)
    db["countries"].insert_all([
        {"name": "France", "capital": "Paris", "population": 68_000_000},
        {"name": "Germany", "capital": "Berlin", "population": 83_000_000},
        {"name": "Japan", "capital": "Tokyo", "population": 125_000_000},
    ], pk="name", replace=True)
    print(f"Populated {db['countries'].count} rows.")
    # Publish the write as a new Volume generation so later replicas reuse it.
    db_vol.commit()


# @app.web_server: the function is called ONCE at container boot. It must start a
# long-lived HTTP server on the port AI Fabric assigns ($FABRIC_SERVER_PORT) and
# return immediately (subprocess.Popen is non-blocking). AI Fabric probes the port
# until Datasette answers (up to startup_timeout), then forwards every web
# request to it. Datasette owns its own routing, so the endpoint captures all
# paths: the browsable UI at "/" and the JSON API at "/data/countries.json",
# "/-/versions.json", etc.
#
# min_replicas=1 keeps one replica warm so the gateway always has a server to
# forward to (a scale-to-zero first request could outrun the wake window).
@app.web_server(startup_timeout=300, min_replicas=1)
@app.function(image=image, volumes={"/db": db_vol}, timeout=3600)
def serve():
    import os
    import subprocess

    db_path = "/db/data.db"
    _ensure_db(db_path)

    # Bind the port AI Fabric assigned this container; never hard-code it
    # (co-located replicas each get a distinct port).
    port = os.environ["FABRIC_SERVER_PORT"]
    subprocess.Popen(
        ["datasette", "serve", db_path, "--host", "0.0.0.0", "--port", port],
    )

Run it

  1. Deploy the app: blade deploy datasette_publish.py. AI Fabric prints the public URL, https://datasette-publish.apps.run.blade.sh.
  2. On first boot the replica runs _ensure_db, which builds the SQLite database on the Volume and db_vol.commit()s it as a new generation. Later replicas find the file already there and skip straight to serving.
  3. The replica is only marked ready AFTER Datasette answers on the loopback port ($FABRIC_SERVER_PORT), so requests never hit a cold server. Datasette owns all routing under /.
  4. Endpoints are private by default, so send your AI Fabric token. Browsable UI: open https://<app>.apps.run.blade.sh/ with the Authorization: Bearer <FABRIC_TOKEN> header. JSON API: curl -H 'Authorization: Bearer <FABRIC_TOKEN>' 'https://<app>.apps.run.blade.sh/data/countries.json?_shape=array' returns your rows, and /-/versions.json reports the Datasette build.
  5. Datasette gives you filters, facets, and ad-hoc SQL over the UI, with a matching .json view on every page for programmatic access. Stop the app when you're done: blade app stop datasette-publish.

Concepts used: Endpoint, Deployment, Replica

Contact the team

Loading the form…