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
Kivy program for identification & rotation sensing of objects on multi-touch tables.

ObjectViz ObjectViz is a multitouch object detection solution, enabling you to create physical markers out of any reliable multitouch solution. It's e

TangibleDisplay 8 Apr 04, 2022
MODeflattener deobfuscates control flow flattened functions obfuscated by OLLVM using Miasm.

MODeflattener deobfuscates control flow flattened functions obfuscated by OLLVM using Miasm.

Suraj Malhotra 138 Jan 07, 2023
Slientruss3d : Python for stable truss analysis tool

slientruss3d : Python for stable truss analysis tool Desciption slientruss3d is a python package which can solve the resistances, internal forces and

3 Dec 26, 2022
Windows symbol tables for Volatility 3

Windows Symbol Tables for Volatility 3 This repository is the Windows Symbol Table storage for Volatility 3. How to Use $ git clone https://github.com

JPCERT Coordination Center 31 Dec 25, 2022
A code ecosystem that helps to find the equate any formula.

A code ecosystem that helps to find the equate any formula. The good part here is that the code finds the formula needed and/or operates on a formula (performs algebra) on it to give you an answer.

SubtleCoder 1 Nov 23, 2021
Retrieve bank transactions and categorize for budgeting use

Budgeting After trying out some budgeting software, I decided to make my own. selenium_scraper Using the selenium package, this script runs an instanc

Marc 1 Nov 10, 2021
Learning with Peter Norvig's lis.py interpreter

Learning with lis.py This repository contains variations of Peter Norvig's lis.py interpreter for a subset of Scheme, described in (How to Write a (Li

Fluent Python 170 Dec 15, 2022
Bitflip Fault Simulation Platform by Daniele Rizzieri (2021)

SEE Injection Framework 2021 This repository contains two Single Event Effect (SEE) injection platforms. The first one is called BFSP - "Bitflip Fault

Daniele Rizzieri 2 Nov 05, 2022
Git Hooks Tutorial.

Git Hooks Tutorial My public talk about this project at Sberloga: Git Hooks Is All You Need 1. Git Hooks 101 Init git repo: mkdir git_repo cd git_repo

Dani El-Ayyass 17 Oct 12, 2022
We are building an open database of COVID-19 cases with chest X-ray or CT images.

🛑 Note: please do not claim diagnostic performance of a model without a clinical study! This is not a kaggle competition dataset. Please read this pa

Joseph Paul Cohen 2.9k Dec 30, 2022
Sailwind Mod Manager

Sailwind Mod Manager The Sailwind Mod Manager is an open source mod manager for the Sailwind community. It currently allows you to browse and download

Max 3 Jul 15, 2022
A python program to detect rickrolls with just the youtube link.

rickroll_detector A python program to detect rickrolls with just the youtube link. Usage: clone this repo or download zip run the main.py file with py

Tricky 4 Nov 06, 2022
PhD document for navlab

PhD_document_for_navlab The project contains the relative software documents which I developped or used during my PhD period. It includes: FLVIS. A st

ZOU YAJING 9 Feb 21, 2022
Transpiles some Python into human-readable Golang.

pytago Transpiles some Python into human-readable Golang. Try out the web demo Installation and usage There are two "officially" supported ways to use

Michael Phelps 318 Jan 03, 2023
Collie is for uncovering RDMA NIC performance anomalies

Collie is for uncovering RDMA NIC performance anomalies. Overview Prerequ

Bytedance Inc. 34 Dec 11, 2022
Tutorials on advanced python topics, and literate programming framework to write them.

Advanced course on Python3 This course covers several topics Python decorators The python object system / meta classes Also see my text on Python impo

Michael Moser 59 Dec 19, 2022
A Python 3 client for the beanstalkd work queue

Greenstalk Greenstalk is a small and unopinionated Python client library for communicating with the beanstalkd work queue. The API provided mostly map

Justin Mayhew 67 Dec 08, 2022
List of short Codeforces problems with a statement of 1000 characters or less. Python script and data files included.

Shortest problems on Codeforces List of Codeforces problems with a short problem statement of 1000 characters or less. Sorted for each rating level. B

32 Dec 24, 2022
Tools, guides, and resources for blockchain analysts to interface with data on the Ergo platform.

Ergo Intelligence Objective Provide a suite of easy-to-use toolkits, guides, and resources for blockchain analysts and data scientists to quickly unde

Chris 5 Mar 15, 2022
Runtime fault injection platform by Daniele Rizzieri (2021)

GDBitflip [v1.04] Runtime fault injection platform by Daniele Rizzieri (2021) This platform executes N times a binary and during each execution it inj

Daniele Rizzieri 1 Dec 07, 2021