CtrlK
BlogDocsLog inGet started
Tessl Logo

tessl/pypi-shiny

A web development framework for Python that enables building fast, beautiful, and interactive web applications using reactive programming principles.

Pending
Overview
Eval results
Files

render.mddocs/

Output Rendering

Shiny's rendering system converts Python objects into web-displayable content. Render functions create reactive outputs that automatically update when their dependencies change, supporting text, plots, tables, images, and dynamic UI content.

Capabilities

Text Rendering

Functions for rendering text content in various formats.

def render.text(fn: Callable[[], str] | None = None, *, inline: bool = False) -> text:
    """
    Render text output.
    
    Args:
        fn: Function that returns a string to display.
        inline: Whether to render as inline text.
        
    Returns:
        Text renderer instance.
    """

def render.code(fn: Callable[[], str] | None = None, *, placeholder: bool = True) -> code:
    """
    Render code block with syntax formatting.
    
    Args:
        fn: Function that returns code as a string.
        placeholder: Whether to show placeholder when content is empty.
        
    Returns:
        Code renderer instance.
    """

Usage Examples

# Basic text output
@output
@render.text
def summary():
    return f"Dataset has {len(data())} rows and {len(data().columns)} columns"

# Multi-line text
@output
@render.text
def analysis_report():
    stats = calculate_stats()
    return f"""
    Analysis Report
    ===============
    Mean: {stats['mean']:.2f}
    Median: {stats['median']:.2f}
    Standard Deviation: {stats['std']:.2f}
    """

# Code output with syntax highlighting
@output
@render.code
def generated_code():
    params = input.model_params()
    return f"""
    import pandas as pd
    import numpy as np
    
    # Generated model configuration
    model = LinearRegression(
        fit_intercept={params['fit_intercept']},
        alpha={params['alpha']}
    )
    """

Plot Rendering

Support for rendering various plot types including matplotlib, plotly, and other visualization libraries.

def render.plot(
    fn: Callable[[], object],
    *,
    alt: str | None = None,
    width: int | float | str = "auto",
    height: int | float | str = "auto",
    **kwargs: object
) -> OutputRenderer[object]:
    """
    Render plot output.
    
    Args:
        fn: Function that returns a plot object (matplotlib, plotly, etc.).
        alt: Alt text for accessibility.
        width: Plot width in pixels or CSS units.
        height: Plot height in pixels or CSS units.
        **kwargs: Additional arguments passed to the plotting backend.
        
    Returns:
        Output renderer for plot content.
    """

Usage Examples

import matplotlib.pyplot as plt
import plotly.express as px
import seaborn as sns

# Matplotlib plot
@output
@render.plot
def scatter_plot():
    df = filtered_data()
    
    plt.figure(figsize=(10, 6))
    plt.scatter(df['x'], df['y'], alpha=0.6)
    plt.xlabel(input.x_variable())
    plt.ylabel(input.y_variable())
    plt.title(f"Scatter Plot: {input.x_variable()} vs {input.y_variable()}")
    plt.grid(True, alpha=0.3)
    
    return plt.gcf()  # Return current figure

# Plotly plot
@output
@render.plot
def interactive_plot():
    df = filtered_data()
    
    fig = px.scatter(
        df, 
        x=input.x_var(), 
        y=input.y_var(),
        color=input.color_var() if input.color_var() else None,
        title="Interactive Scatter Plot",
        hover_data=['id', 'category']
    )
    
    return fig

# Seaborn plot
@output
@render.plot(width=800, height=600)
def correlation_heatmap():
    df = numeric_data()
    
    plt.figure(figsize=(10, 8))
    sns.heatmap(
        df.corr(), 
        annot=True, 
        cmap='coolwarm', 
        center=0,
        square=True
    )
    plt.title("Correlation Matrix")
    
    return plt.gcf()

Image Rendering

Render static and dynamic images from various sources.

def render.image(
    fn: Callable[[], ImgData | str | bytes | os.PathLike[str]],
    **kwargs: object
) -> OutputRenderer[ImgData | str | bytes | os.PathLike[str]]:
    """
    Render image output.
    
    Args:
        fn: Function that returns image data, file path, or ImgData dict.
        **kwargs: Additional image attributes (alt, width, height, etc.).
        
    Returns:
        Output renderer for image content.
    """

Usage Examples

import io
import base64
from PIL import Image

# Render image from file path
@output
@render.image
def logo():
    return "static/company_logo.png"

# Generate image dynamically
@output
@render.image
def generated_chart():
    # Create image using PIL
    img = Image.new('RGB', (400, 300), color='lightblue')
    draw = ImageDraw.Draw(img)
    
    # Draw some content based on inputs
    draw.text((20, 20), f"Value: {input.current_value()}", fill='black')
    
    # Convert to bytes
    img_bytes = io.BytesIO()
    img.save(img_bytes, format='PNG')
    img_bytes.seek(0)
    
    return img_bytes.getvalue()

# Return ImgData dictionary for full control
@output
@render.image
def custom_image():
    image_path = generate_custom_visualization(input.params())
    
    return {
        "src": image_path,
        "width": "100%",
        "height": "400px",
        "alt": "Custom visualization based on user parameters",
        "style": "border: 1px solid #ddd; border-radius: 4px;"
    }

Table Rendering

Render tabular data with basic formatting.

def render.table(
    fn: Callable[[], object],
    **kwargs: object
) -> OutputRenderer[object]:
    """
    Render table output.
    
    Args:
        fn: Function that returns tabular data (DataFrame, dict, list of dicts, etc.).
        **kwargs: Additional table formatting options.
        
    Returns:
        Output renderer for table content.
    """

Usage Examples

# Render pandas DataFrame
@output
@render.table
def data_summary():
    df = filtered_data()
    return df.describe()

# Render list of dictionaries
@output
@render.table
def results_table():
    results = process_analysis()
    return [
        {"Metric": "Accuracy", "Value": results['accuracy'], "Threshold": 0.9},
        {"Metric": "Precision", "Value": results['precision'], "Threshold": 0.8},
        {"Metric": "Recall", "Value": results['recall'], "Threshold": 0.75}
    ]

# Render dictionary as key-value table
@output
@render.table
def configuration():
    return {
        "Model Type": input.model_type(),
        "Training Size": len(training_data()),
        "Features": ", ".join(input.selected_features()),
        "Last Updated": datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    }

Data Frame Rendering

Interactive data frame rendering with advanced features like sorting, filtering, and editing.

def render.data_frame(
    fn: Callable[[], object],
    *,
    width: str | float = "fit-content",
    height: str | float = "500px",
    summary: bool | str = True,
    filters: bool = False,
    editable: bool = False,
    **kwargs: object
) -> DataFrameRenderer:
    """
    Render interactive data frame.
    
    Args:
        fn: Function that returns a pandas DataFrame or similar.
        width: Data frame width.
        height: Data frame height.
        summary: Show summary information.
        filters: Enable column filtering.
        editable: Allow cell editing.
        **kwargs: Additional data frame options.
        
    Returns:
        Data frame renderer with interaction capabilities.
    """

class DataGrid:
    """
    Configuration for data grid rendering.
    """
    def __init__(
        self,
        *,
        filters: bool = False,
        editable: bool = False,
        summary: bool | str = True,
        **kwargs: object
    ): ...

class DataTable:
    """
    Configuration for data table rendering.
    """
    def __init__(
        self,
        *,
        page_size: int = 10,
        searchable: bool = True,
        sortable: bool = True,
        **kwargs: object
    ): ...

Usage Examples

# Basic interactive data frame
@output
@render.data_frame
def dataset_view():
    return filtered_data()

# Data frame with filtering and editing
@output
@render.data_frame(
    filters=True,
    editable=True,
    height="600px"
)
def editable_data():
    return working_dataset()

# Data grid configuration
@output
@render.data_frame
def analysis_results():
    df = compute_results()
    
    # Configure as data grid
    return render.DataGrid(
        df,
        filters=True,
        summary="Data from analysis pipeline",
        editable=False
    )

# Data table with pagination
@output
@render.data_frame
def large_dataset():
    df = get_large_dataset()
    
    return render.DataTable(
        df,
        page_size=25,
        searchable=True,
        sortable=True
    )

UI Rendering

Render dynamic UI content that can change based on reactive state.

def render.ui(
    fn: Callable[[], Tag | TagChild | None]
) -> OutputRenderer[Tag | TagChild | None]:
    """
    Render dynamic UI content.
    
    Args:
        fn: Function that returns UI elements (Tag, TagChild, or None).
        
    Returns:
        Output renderer for UI content.
    """

Usage Examples

# Dynamic input controls
@output
@render.ui
def dynamic_inputs():
    dataset_type = input.data_type()
    
    if dataset_type == "csv":
        return ui.div(
            ui.input_file("csv_file", "Upload CSV file"),
            ui.input_checkbox("has_header", "File has header row", True)
        )
    elif dataset_type == "database":
        return ui.div(
            ui.input_text("db_connection", "Database Connection String"),
            ui.input_text("query", "SQL Query")
        )
    else:
        return ui.p("Please select a data source type")

# Conditional content based on analysis
@output
@render.ui
def analysis_options():
    if not data_loaded():
        return ui.div(
            ui.h4("No Data Loaded"),
            ui.p("Please upload data to begin analysis")
        )
    
    df = current_data()
    numeric_cols = df.select_dtypes(include=[np.number]).columns.tolist()
    
    return ui.div(
        ui.h4("Analysis Options"),
        ui.input_select(
            "x_variable",
            "X Variable",
            choices=numeric_cols
        ),
        ui.input_select(
            "y_variable",
            "Y Variable",
            choices=numeric_cols
        ),
        ui.input_checkbox_group(
            "analysis_types",
            "Analysis Types",
            choices=["correlation", "regression", "clustering"]
        )
    )

# Dynamic content with complex logic
@output
@render.ui
def status_dashboard():
    system_status = check_system_status()
    
    status_color = "success" if system_status["healthy"] else "danger"
    
    return ui.div(
        ui.div(
            ui.h3("System Status", class_=f"text-{status_color}"),
            ui.p(f"Status: {system_status['message']}"),
            class_=f"alert alert-{status_color}"
        ),
        ui.div(
            [ui.p(f"{service}: {'✓' if status else '✗'}") 
             for service, status in system_status["services"].items()],
            class_="service-status"
        ),
        ui.div(
            ui.input_action_button(
                "refresh_status", 
                "Refresh Status",
                class_="btn btn-secondary"
            )
        )
    )

Download Handling

Create downloadable files for users.

def render.download(
    fn: Callable[[str], None],
    filename: str | Callable[[], str] | None = None,
    media_type: str = "application/octet-stream"
) -> DownloadHandler:
    """
    Create a download handler.
    
    Args:
        fn: Function that writes content to the provided file path.
        filename: Default filename or function that returns filename.
        media_type: MIME type of the downloaded content.
        
    Returns:
        Download handler for file downloads.
    """

class DownloadHandler:
    """
    Handler for file downloads.
    """
    def set_filename(self, filename: str | Callable[[], str]) -> None:
        """Set the download filename."""
    
    def set_media_type(self, media_type: str) -> None:
        """Set the MIME type."""

Usage Examples

# Download CSV data
@output
@render.download(filename="data_export.csv")
def download_csv(file):
    df = filtered_data()
    df.to_csv(file, index=False)

# Download plot as image
@output
@render.download(
    filename=lambda: f"plot_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png",
    media_type="image/png"
)
def download_plot(file):
    fig = generate_current_plot()
    fig.savefig(file, format='png', dpi=300, bbox_inches='tight')

# Download analysis report
@output
@render.download(filename="analysis_report.pdf")
def download_report(file):
    analysis_results = run_complete_analysis()
    
    # Generate PDF report
    pdf = create_pdf_report(analysis_results)
    pdf.output(file)

# Dynamic filename and content
@output
@render.download()
def download_custom(file):
    export_format = input.export_format()
    data = current_dataset()
    
    if export_format == "csv":
        data.to_csv(file, index=False)
        return f"data_export_{datetime.now().strftime('%Y%m%d')}.csv"
    elif export_format == "json":
        data.to_json(file, orient='records', indent=2)
        return f"data_export_{datetime.now().strftime('%Y%m%d')}.json"
    elif export_format == "excel":
        data.to_excel(file, index=False)
        return f"data_export_{datetime.now().strftime('%Y%m%d')}.xlsx"

Express Rendering

Special rendering decorator for Express mode applications.

def render.express(
    fn: Callable[[], object]
) -> object:
    """
    Express-style rendering decorator.
    
    Args:
        fn: Function that returns content to render.
        
    Returns:
        Rendered content for Express mode.
    """

Usage Examples

# Express mode rendering (in express apps)
from shiny.express import render, input, ui

# Automatic output binding in Express mode
@render.text
def current_status():
    return f"Processing {input.selected_file()}"

@render.plot  
def main_visualization():
    return create_plot(input.parameters())

# Express rendering works with all render types
@render.data_frame
def results_table():
    return analyze_data(input.dataset(), input.options())

Render Transformers

Utilities for transforming render output.

class render.transformer:
    """
    Utilities for transforming render output.
    """
    @staticmethod
    def cache_disk(
        cache_dir: str | os.PathLike[str] | None = None,
        max_size: int | None = None
    ) -> Callable[[Callable], Callable]: ...
    
    @staticmethod
    def cache_memory(
        max_size: int = 128
    ) -> Callable[[Callable], Callable]: ...

Usage Examples

# Cache expensive computations to disk
@output
@render.plot
@render.transformer.cache_disk(cache_dir="./plot_cache", max_size=100)
def expensive_plot():
    # This plot will be cached to disk
    return generate_complex_visualization(large_dataset())

# Cache in memory
@output
@render.table
@render.transformer.cache_memory(max_size=50)
def analysis_summary():
    # Results cached in memory
    return compute_summary_statistics(input.dataset())

Install with Tessl CLI

npx tessl i tessl/pypi-shiny

docs

app.md

express.md

index.md

reactive.md

render.md

session.md

types.md

ui.md

tile.json