A framework to create reusable Dash layout.

Overview

dash_component_template

https://img.shields.io/badge/gh--pages-doc-brightgreen https://codecov.io/gh/toltec-astro/dash_component_template/branch/main/graph/badge.svg?token=4Z2P2IPL1U

A framework to create reusable Dash layout.

Features

This package provides a new API for creating Dash layout and callbacks.

  • The id and children are managed automatically. No deeply nested dicts and lists any more; unique ids of components are automatically created.
  • A re-usable template can be defined by sub-classing dash_component_template.ComponentTemplate. Instances of the template have children with unique ids and can be used anywhere in anyway inside a larger Dash app layout tree.

Get Started

Suppose we have the following Dash app (from Dash tutorial site):

# Run this app with `python app.py` and
# visit http://127.0.0.1:8050/ in your web browser.

import dash
from dash import dcc, html
import plotly.express as px
import pandas as pd

app = dash.Dash(__name__)

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options
df = pd.DataFrame({
    "Fruit": ["Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
    "Amount": [4, 1, 2, 2, 4, 5],
    "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
})

fig = px.bar(df, x="Fruit", y="Amount", color="City", barmode="group")

app.layout = html.Div(children=[
    html.H1(children='Hello Dash'),

    html.Div(children='''
        Dash: A web application framework for your data.
    '''),

    dcc.Graph(
        id='example-graph',
        figure=fig
    )
])

if __name__ == '__main__':
    app.run_server(debug=True)

Let's build a new app which have two columns of the same layout.

from dash_component_template import ComponentTemplate
import dash_bootstrap_components as dbc
import pandas as pd
import dash
import plotly.express as px
from dash import html, dcc


# This class defines a template that resembles the Dash example,
# with a title, subtitle, and graph for visualizing a data frame
class MyTableGraph(ComponentTemplate):

    class Meta:
        component_cls = dbc.Container

    def __init__(self, title_text, subtitle_text, df, parent=None):
        super().__init__(parent=parent)
        self._title_text = title_text
        self._subtitle_text = subtitle_text
        self._df = df

    def setup_layout(self, app):
        container = self
        container.child(html.Div, self._title_text)
        container.child(html.Div, self._subtitle_text)
        container.child(dcc.Graph, figure=self._make_fig())
        super().setup_layout(app)

    def _make_fig(self):
        return px.bar(
            self._df, x="Fruit", y="Amount", color="City", barmode="group")


# This class defines the app layout which have two columns each column
# contains an instance of the template defined above.

class MyPage(ComponentTemplate):

    class Meta:
        component_cls = dbc.Container

    # define some data
    df1 = pd.DataFrame({
        "Fruit": [
            "Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
        "Amount": [4, 1, 2, 2, 4, 5],
        "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
    })

    df2 = pd.DataFrame({
        "Fruit": [
            "Apples", "Oranges", "Bananas", "Apples", "Oranges", "Bananas"],
        "Amount": [5, 6, 7, 8, 4, 5],
        "City": ["SF", "SF", "SF", "Montreal", "Montreal", "Montreal"]
    })

    def setup_layout(self, app):
        col1, col2 = self.grid(nrows=1, ncols=2, squeeze=True)
        col1.child(MyTableGraph(
            df=self.df1,
            title_text='Hello Dash (left)',
            subtitle_text='Re-usable template instance 1'
            ))
        col2.child(MyTableGraph(
            df=self.df2,
            title_text='Hello Dash (right)',
            subtitle_text='Re-usable template instance 2'
            ))
        # this line is important which triggers children's setup_layout
        super().setup_layout(app)


# Now create the app and set the bootstrap css
app = dash.Dash(__name__, external_stylesheets=[dbc.themes.BOOTSTRAP])

# Instantiant the page tempalte, and call the setup layout function
# This only "declare" the structure of the Dash components. No actual
# Dash components are created yet.
page = MyPage()
page.setup_layout(app)
# Create and assign the app layout. The actual creation of Dash components
# are done here.
app.layout = page.layout

if __name__ == '__main__':
    app.run_server(debug=True)

Live Examples

Live examples can be found in the TolTEC DR site.

Credits

This package was created with Cookiecutter and the audreyr/cookiecutter-pypackage project template.

You might also like...
Create VSCode Extensions with python
Create VSCode Extensions with python

About Create vscode extensions with python. Installation Stable version: pip install vscode-ext Why use this? Why should you use this for building VSc

The only purpose of a byte-sized application is to help you create .desktop entry files for downloaded applications.
The only purpose of a byte-sized application is to help you create .desktop entry files for downloaded applications.

Turtle 🐢 The only purpose of a byte-sized application is to help you create .desktop entry files for downloaded applications. As of usual with elemen

✔️ Create to-do lists to easily manage your ideas and work.

Todo List + Add task + Remove task + List completed task + List not completed task + Set clock task time + View task statistics by date Changelog v 1.

KUIZ is a web application quiz where you can create/take a quiz for learning and sharing knowledge from various subjects, questions and answers.

KUIZ KUIZ is a web application quiz where you can create/take a quiz for learning and sharing knowledge from various subjects, questions and answers.

Fetch data from an excel file and create HTML file

excel-to-html Problem Statement! - Fetch data from excel file and create html file Excel.xlsx file contain the information.in multiple rows that is ne

Allow you to create you own custom decentralize job management system.

ants Allow you to create you own custom decentralize job management system. Install $ git clone https://github.com/hvuhsg/ants.git Run monitor exampl

A Linux program to create a Windows USB stick installer from a real Windows DVD or image.
A Linux program to create a Windows USB stick installer from a real Windows DVD or image.

WoeUSB-ng A Linux program to create a Windows USB stick installer from a real Windows DVD or image. This package contains two programs: woeusb: A comm

Create or join a private chatroom without any third-party middlemen in less than 30 seconds, available through an AES encrypted password protected link.
Create or join a private chatroom without any third-party middlemen in less than 30 seconds, available through an AES encrypted password protected link.

PY-CHAT Create or join a private chatroom without any third-party middlemen in less than 30 seconds, available through an AES encrypted password prote

Simply create JIRA releases based on your github releases

Simply create JIRA releases based on your github releases

Releases(v0.1.0)
Owner
The TolTEC Project
TolTEC is a new millimeter-wavelength camera that takes maximal advantage of the Large Millimeter Telescope
The TolTEC Project
Zeus is an open source flight intellingence tool which supports more than 13,000+ airlines and 250+ countries.

Zeus Zeus is an open source flight intellingence tool which supports more than 13,000+ airlines and 250+ countries. Any flight worldwide, at your fing

DeVickey 1 Oct 22, 2021
vFuzzer is a tool developed for fuzzing buffer overflows, For now, It can be used for fuzzing plain vanilla stack based buffer overflows

vFuzzer vFuzzer is a tool developed for fuzzing buffer overflows, For now, It can be used for fuzzing plain vanilla stack based buffer overflows, The

Vedant Bhalgama 5 Nov 12, 2022
A python script to make leaderboards using a CSV with the runners name, IDs and Flag Emojis

SrcLbMaker A python script to make speedrun.com global leaderboards. Installation You need python 3.6 or higher. First, go to the folder where you wan

2 Jul 25, 2022
decorator

Decorators for Humans The goal of the decorator module is to make it easy to define signature-preserving function decorators and decorator factories.

Michele Simionato 734 Dec 30, 2022
Restaurant-finder - Restaurant finder With Python

restaurant-finder APIs /restaurants query-params: a. filter: column based on whi

Kumar saurav 1 Feb 22, 2022
A streaming animation of all the edits to a given Wikipedia page.

WikiFilms! What is it? A streaming animation of all the edits to a given Wikipedia page. How it works. It works by creating a "virtual camera," which

Tal Zaken 2 Jan 18, 2022
Coded in Python 3 - I make for education, easily clone simple website.

Simple Website Cloner - Single Page Coded in Python 3 - I make for education, easily clone simple website. How to use ? Install Python 3 first. Instal

Phạm Đức Thanh 2 Jan 13, 2022
A Python program that generates a maze that solves itself using DFS

Maze Generator And Solver Program Purpose: Generates a maze that then solves itself Language: Python and Pygame Algorithm: Randomized DFS / Floodfill

Joshua Liu 1 Jul 25, 2022
Step by step development of a vending coffee machine project, including tkinter, sqlite3, simulation, etc.

Step by step development of a vending coffee machine project, including tkinter, sqlite3, simulation, etc.

Nikolaos Avouris 2 Dec 05, 2021
Dungeon Dice Rolls is an aplication that the user can roll dices (d4, d6, d8, d10, d12, d20 and d100) and store the results in one of the 6 arrays.

Dungeon Dice Rolls is an aplication that the user can roll dices (d4, d6, d8, d10, d12, d20 and d100) and store the results in one of the 6 arrays.

Bracero 1 Dec 31, 2021
A Python package for searching journal publications and researchers

scholarpy A python package for searching journal publications and researchers Free software: MIT license Documentation: https://giswqs.github.io/schol

Qiusheng Wu 8 Mar 12, 2022
Structured Exceptions for Python

XC: Structured exceptions for Python XC encourages a structured, disciplined approach to use of exceptions: it reduces the overhead of declaring excep

Bob Gautier 2 May 28, 2021
Library for RadiaCode-101

RadiaCode Библиотека для работы с дозиметром RadiaCode-101, находится в разработке - API не стабилен и возможны изменения. Пример использования (backe

Maxim Andreev 56 Nov 29, 2022
Karte der Allgemeinverfügungen zu Schulschließungen oder eingeschränktem Regelbetrieb in Sachsen

SNSZ Karte Datenquelle: Allgemeinverfügungen zu Schulschließungen oder eingeschränktem Regelbetrieb in Sachsen Sächsisches Staatsministerium für Kultu

Jannis Leidel 3 Sep 26, 2022
SuperCollider library for Python

SuperCollider library for Python This project is a port of core features of SuperCollider's language to Python 3. It is intended to be the same librar

Lucas Samaruga 65 Dec 22, 2022
A minimalist production ready plugin system

pluggy - A minimalist production ready plugin system This is the core framework used by the pytest, tox, and devpi projects. Please read the docs to l

pytest-dev 876 Jan 05, 2023
Program Input Data Mahasiswa Oop

PROGRAM INPUT NILAI MAHASISWA MENGGUNAKAN OOP PENGERTIAN OOP object-oriented-programing/OOP adalah paradigma pemrograman berdasarkan konsep "objek", y

Maulana Reza Badrudin 1 Jan 05, 2022
Online-update est un programme python permettant de mettre a jour des dossier et de fichier depuis une adresse web.

Démarrage rapide Online-update est un programme python permettant de mettre a jour des dossier et de fichier depuis une adresse web. Mode préconfiguré

pf4 2 Nov 26, 2021
Cloud-native SIEM for intelligent security analytics for your entire enterprise.

Microsoft Sentinel Welcome to the Microsoft Sentinel repository! This repository contains out of the box detections, exploration queries, hunting quer

Microsoft Azure 2.9k Jan 02, 2023
CountdownTimer - Countdown Timer For Python

Countdown Timer This python script asks for the user time (input) in seconds, an

Arinzechukwu Okoye 1 Jan 01, 2022