ipyfilechooser

Let a Shiny app browse and pick files that already live on the server, sandboxed to a directory you choose.

ipyfilechooser lets a Shiny app browse and pick files that already live on the server’s filesystem. The decorated function returns an ipyfilechooser.FileChooser; @render_ipyfilechooser renders it at its natural, unfilled size and round-trips a confirmed selection back to Python.

hero

A CSV picked from the server’s own filesystem feeds a table and a plot. Try the app.

Installation

pip install 'shinywidgets[ipyfilechooser]'

Quick start

A chooser rooted at a directory, with the confirmed selection read back into a reactive.value via register_callback().

import os
import tempfile

from ipyfilechooser import FileChooser
from shiny import reactive, render
from shiny.express import ui
from shinywidgets import render_ipyfilechooser

def make_sample_dir() -> str:
    """A couple of sample files to browse (created fresh each run)."""
    data_dir = tempfile.mkdtemp(prefix="shinywidgets-quickstart-")
    for name in ("notes.txt", "report.csv"):
        with open(os.path.join(data_dir, name), "w") as f:
            f.write(f"sample contents of {name}\n")
    return data_dir


DATA_DIR = make_sample_dir()

ui.page_opts(title="ipyfilechooser quickstart")

selected_path = reactive.value(None)

with ui.card():

    @render_ipyfilechooser
    def chooser():
        fc = FileChooser(path=DATA_DIR)
        # `selected` is a plain property, not a trait: a callback -- not
        # reactive_read() -- is how a confirmed pick reaches Python
        fc.register_callback(lambda fc: selected_path.set(fc.selected))
        return fc

    @render.text
    def selected():
        return f"Selected: {selected_path()}"

The chooser renders at its natural width and doesn’t stretch to fill the card.

Overview

A look at what you can build. Click any of them to open the app, with its code, in Shinylive.

Server files, not uploads

This widget browses the server’s filesystem, not the visitor’s:

ui.input_file() @render_ipyfilechooser
Browses the visitor’s device the Shiny server’s filesystem
Data moves browser -> server (upload) nowhere – selection is just a path
Good fit public apps, user-supplied data internal tools, a single-tenant app, a data directory you control
Risk if unsandboxed none beyond upload size lets a user read/discover arbitrary server-readable files

If your app is multi-tenant or public-facing, wall the user into a directory with sandbox_path (a per-user scratch folder, a shared read-only data drop), and pair it with filter_pattern to keep them on relevant files. show_only_dirs=True and the default show_hidden=False further narrow what a sandboxed browser can surface.

Sandboxing

Yes, for the normal UI-driven paths: the path dropdown and the file/directory listing are built from the filesystem under sandbox_path and never offer an entry outside it, and navigating a listed subdirectory can’t leave the sandbox, since it’s a real subdirectory below sandbox_path.

The one place a user could try to escape is the filename text field, by typing something like ../secret.txt. ipyfilechooser rejects that as invalid and disables the Select/Change button until the field holds a safe name, so the attempt never reaches Python:

sandbox escape blocked

That protection lives entirely in the browser, though: nothing on the server re-validates a filename against sandbox_path before accepting it. A user clicking around the rendered UI can’t escape the sandbox, but a client that bypasses the UI can still submit an out-of-sandbox path in .selected. The sandbox reliably limits what a browsing user can see, but .selected itself is still client-supplied input – if your app reads the selected file and serves its contents back, validate the resolved path yourself:

import os

sandbox = os.path.realpath("/safe/directory")


def inside_sandbox(path: str) -> bool:
    resolved = os.path.realpath(path)
    return resolved == sandbox or resolved.startswith(sandbox + os.sep)

Reacting to interaction

This renderer has no reactive accessors: FileChooser’s selection (selected, selected_path, selected_filename) is a plain Python property, not a widget trait. reactive_read(), .read(), and an accessor method all depend on a trait to invalidate from, so none of them work here – reach for register_callback() instead.

register_callback()

FileChooser.register_callback(fn) calls fn with the chooser whenever the user confirms a selection. The idiomatic bridge to Shiny has that callback set a reactive.value, as in Quick start above.

Set show_only_dirs=True and the listing shows only subdirectories; a single click on a row navigates into it, and confirming with Select/Change applies the current directory as selected_path. Feed that into a plain data frame built from os.scandir():

import os
import tempfile

import pandas as pd
from ipyfilechooser import FileChooser
from shiny import reactive, render, req
from shiny.express import ui
from shinywidgets import render_ipyfilechooser


def make_project_dir() -> str:
    """A small project tree: a few subdirectories, each with a few files."""
    root = tempfile.mkdtemp(prefix="shinywidgets-project-")
    for sub, files in {
        "data": ["gapminder.csv", "tips.csv"],
        "notebooks": ["exploration.ipynb"],
        "src": ["app.py", "utils.py", "__init__.py"],
    }.items():
        os.makedirs(os.path.join(root, sub))
        for name in files:
            with open(os.path.join(root, sub, name), "w") as f:
                f.write(name * 20)  # a little bulk so sizes aren't all 0
    return root


PROJECT_DIR = make_project_dir()

ui.page_opts(title="Pick a directory, list its contents")

picked_dir = reactive.value(PROJECT_DIR)

with ui.card():

    @render_ipyfilechooser
    def dirpicker():
        fc = FileChooser(
            path=PROJECT_DIR,
            sandbox_path=PROJECT_DIR,
            show_only_dirs=True,
            title="Pick a subdirectory",
        )
        fc.register_callback(lambda fc: picked_dir.set(fc.selected_path))
        return fc

    @render.data_frame
    def contents():
        req(picked_dir())
        entries = []
        with os.scandir(picked_dir()) as it:
            for entry in it:
                entries.append(
                    {
                        "name": entry.name,
                        "kind": "dir" if entry.is_dir() else "file",
                        "size": entry.stat().st_size,
                    }
                )
        return pd.DataFrame(entries).sort_values(["kind", "name"])

The reactive value is seeded with the project root, so the listing shows immediately:

What to know about the callback itself:

  • Fires on confirm, not on every keystroke or navigation: browsing the listing or editing the filename field doesn’t call it, only the button click that applies a selection does.
  • One callback per chooser: register_callback() overwrites the previous one, so compose more than one effect inside the function you register.
  • A re-render gives the user a brand-new FileChooser with no selection: re-running the decorated function discards the old chooser and mounts a fresh one.
  • select_default=True doesn’t fire the callback: constructing a chooser with filename="app.py", select_default=True shows app.py as selected in the UI, but the callback only runs on a confirmed pick. Seed your reactive.value with that same default yourself.
  • .reset(path=...) doesn’t fire the callback either, but does silently reapply select_default: calling it re-selects the default filename in the new path without invoking your callback. Re-read fc.selected yourself right after, if you mirror it elsewhere.

fc.show_hidden, fc.filter_pattern, and fc.sandbox_path just return whatever you set – reading them tells you nothing you don’t already know from your own inputs.

Updating in place

Three FileChooser properties are real setters that refresh the rendered chooser in place – no re-render, no lost in-flight navigation:

  • chooser.widget.show_hidden = True/False
  • chooser.widget.filter_pattern = [...] (or None to clear it)
  • chooser.widget.reset(path=..., filename=...) – jump to a new starting location (and optionally seed a filename); clears any current selection, and closes the dialog if it was open.
import os
import tempfile

from ipyfilechooser import FileChooser
from shiny import reactive, render
from shiny.express import input, ui
from shinywidgets import render_ipyfilechooser


def make_project_dir() -> str:
    root = tempfile.mkdtemp(prefix="shinywidgets-controlled-")
    os.makedirs(os.path.join(root, "data"))
    os.makedirs(os.path.join(root, "src"))
    for name in ("data/gapminder.csv", "data/tips.csv", "src/app.py", "notes.md"):
        with open(os.path.join(root, name), "w") as f:
            f.write("sample\n")
    with open(os.path.join(root, ".env"), "w") as f:
        f.write("SECRET=shh\n")
    return root


ROOT = make_project_dir()
BOOKMARKS = {"root": ROOT, "data": os.path.join(ROOT, "data"), "src": os.path.join(ROOT, "src")}

ui.page_opts(title="Steering the chooser from Shiny inputs")

with ui.sidebar():
    ui.input_select("jump", "Jump to", choices=list(BOOKMARKS))
    ui.input_checkbox("hidden", "Show hidden files", False)
    ui.input_select(
        "filter", "Filter", choices={"none": "all files", "csv": "*.csv", "py": "*.py"}
    )

selected_path = reactive.value(None)

with ui.card():

    @render_ipyfilechooser
    def chooser():
        fc = FileChooser(path=ROOT, sandbox_path=ROOT)
        fc.register_callback(lambda fc: selected_path.set(fc.selected))
        return fc

    @render.text
    def selected():
        return f"Selected: {selected_path()}"


# Python -> browser: jump the chooser to a bookmarked folder. reset() clears
# any current selection, so clear the mirrored reactive.value too
@reactive.effect
def _jump():
    chooser.widget.reset(path=BOOKMARKS[input.jump()])
    selected_path.set(None)


# These setters refresh the chooser's listing in place -- no re-render, and
# the user's current path and any confirmed selection are left untouched
@reactive.effect
def _toggle_hidden():
    chooser.widget.show_hidden = input.hidden()


@reactive.effect
def _set_filter():
    f = input.filter()
    chooser.widget.filter_pattern = None if f == "none" else [f"*.{f}"]

Re-running the decorated function would tear down and rebuild the whole chooser, losing any in-flight dialog state, on every sidebar change. Driving .widget’s setters from a @reactive.effect instead leaves the user’s place in the directory tree untouched. See Updating in place for the general pattern.

If you combine select_default=True with a Python-driven reset(), an effect that calls .reset(path=...) in response to an input also runs once at startup, immediately reapplying select_default’s pick before the user ever touches the input. Gate the effect with @reactive.event(input.jump, ignore_init=True) so it only fires on an actual change.

Linking widgets

Preview a picked CSV

Sandboxed to a data directory and filtered to *.csv, a confirmed pick feeds an itables table and a plotly figure from the same file:

import os
import tempfile

import pandas as pd
import plotly.express as px
from ipyfilechooser import FileChooser
from shiny import reactive, render, req
from shiny.express import ui
from shinywidgets import render_ipyfilechooser, render_itables, render_plotly


def make_data_dir() -> str:
    """A small sandboxed data directory: two CSVs plus a decoy text file."""
    data_dir = tempfile.mkdtemp(prefix="shinywidgets-preview-")
    gapminder = px.data.gapminder()
    gapminder[gapminder["year"] == 2007].to_csv(
        os.path.join(data_dir, "gapminder_2007.csv"), index=False
    )
    px.data.tips().to_csv(os.path.join(data_dir, "tips.csv"), index=False)
    with open(os.path.join(data_dir, "README.txt"), "w") as f:
        f.write("Only *.csv files are selectable here (see filter_pattern).\n")
    return data_dir


DATA_DIR = make_data_dir()

ui.page_opts(title="Pick a CSV, preview it", fillable=True)

picked_path = reactive.value(None)

with ui.sidebar(width=320):

    @render_ipyfilechooser
    def picker():
        fc = FileChooser(path=DATA_DIR, sandbox_path=DATA_DIR, filter_pattern=["*.csv"])
        fc.register_callback(lambda fc: picked_path.set(fc.selected))
        return fc


@reactive.calc
def df():
    req(picked_path())
    return pd.read_csv(picked_path())


with ui.layout_columns(col_widths=(6, 6)):
    with ui.card(full_screen=True):
        ui.card_header("Table")

        @render_itables
        def table():
            return df()

    with ui.card(full_screen=True):
        ui.card_header("Plot")

        @render_plotly
        def plot():
            data = df()
            if "lifeExp" in data.columns:
                return px.scatter(
                    data, x="gdpPercap", y="lifeExp", size="pop", color="continent",
                    log_x=True, hover_name="country",
                )
            return px.histogram(data, x="total_bill", color="sex")

filter_pattern=["*.csv"] keeps README.txt out of the listing entirely – opening the dialog shows only gapminder_2007.csv and tips.csv. A req()-gated calc with no value yet is a normal state, not an error.

The same shape works for a file count, a total size, a thumbnail grid, or a second chooser scoped to the one just picked. Combine it with bookmarks and filters steering one chooser and a preview that adapts to the pick, and you get showcase_file_inspector.py.

Layout and sizing

FileChooser renders at its natural size and doesn’t stretch to fill a fillable container, the same as a slider or checkbox would – its width stays the same no matter how tall the surrounding card is.

  • To change the width, set it on the chooser itself: FileChooser(layout=Layout(width="700px")). A user-supplied layout always wins over the default, and a bare FileChooser() with no layout is safe to use in a multi-session app – one session’s width never leaks into another’s.
  • Don’t set a height – there’s nothing to fill; the dialog’s own listing already scrolls (rows= controls how many rows show before it does).
  • output_widget("id", width=...) also works if you’d rather size the output container than the widget itself, but sizing the FileChooser’s own layout is simpler, and is what every example above does.

Learn more