Defer data load

Download this notebook from GitHub (right-click to download).


import panel as pn
import pandas as pd
import hvplot.pandas
import time

pn.extension(sizing_mode="stretch_width")

Defer loading of the data and populating the widgets until the page is rendered:

stocks_url = 'https://raw.githubusercontent.com/vega/datalib/master/test/data/stocks.csv'

select_ticker = pn.widgets.Select(name='Stock Ticker', width=250, sizing_mode="fixed")

def load_data():
    if 'stocks' not in pn.state.cache: 
        pn.state.cache['stocks'] = df = pd.read_csv(stocks_url, parse_dates=['date']).set_index('symbol')
    else:
        df = pn.state.cache['stocks']
    symbols = list(df.index.unique())
    select_ticker.options = symbols
    select_ticker.value = symbols[0]
    
pn.state.onload(load_data)

If 'stocks' is not yet in cache we show a spinner widget, otherwise let us plot the data:

@pn.depends(select_ticker)
def plot_ticker(ticker):
    if 'stocks' not in pn.state.cache or not ticker:
        return pn.indicators.LoadingSpinner(value=True)
    time.sleep(0.5)
    return pn.state.cache['stocks'].loc[ticker].hvplot.line('date', 'price', color="#C01754", line_width=6)

pn.Row(select_ticker, plot_ticker)

App

Lets wrap it into nice template that can be served via panel serve defer_data_load.ipynb

pn.template.FastListTemplate(
    site="Panel", 
    title="Defer Data Load", 
    sidebar=[select_ticker], 
    main=[
        "This app demonstrates how to **defer the loading** of the data and population of the widgets until the page is rendered",
        plot_ticker,
    ]
).servable();
This web page was generated from a Jupyter notebook and not all interactivity will work on this website. Right click to download and run locally for full Python-backed interactivity.

Download this notebook from GitHub (right-click to download).