dash load up with an empty table - python

I am making my first dash application. I am creating a layout which will contain a dash_table however at load up time the table will be empty as the table will populate once the user selects an option.
I have tried setting the dash table to {} & none but when I do this the page will not load. How can I have an empty table as part of my layout when loading the page?

You need to provide a dictionary of column names at least to create an empty datatable. You can leave the data attribute as empty, here is a minimally working example:
from dash import Dash, dash_table, html
app = Dash(__name__)
app.layout = html.Div([
dash_table.DataTable(id="table_infos",
columns=[
{'id': "Intitulé", 'name': "Intitulé"},
{'id': "Donnée", 'name': "Donnée"}
]
)
])
if __name__ == '__main__':
app.run_server(debug=True)

Related

Plotly Dash : Sharing dataframe between pages

I can't find how I can share a dataframe between my different page to avoid to recreate it every time i change of page. Is their a way to create it in the app.py and access it from all pages ? I want to share df_role and df_best_pos
my app.py :
df_role, df_best_pos = build_data_frame()
app = dash.Dash(
__name__,
use_pages=True,
external_stylesheets=[dbc.icons.FONT_AWESOME, "https://rsms.me/inter/inter.css"]
# Loads icons css and Inter font
)
navbar = create_nav_bar()
content = dash.html.Div([dash.page_container], id="pages-content")
app.layout = dash.html.Div([dash.dcc.Location(id="url"), navbar, content])
app.run_server(debug=False, port=3005)

How to display Dash DataTables on Streamlit

I am trying to display a table/dataframe built with dash_table from the dash package on my Streamlit dashboard, but I am getting empty tables/dataframes.
Presumably this is because st.table() and st.dataframe() do not take DataTable objects as input.
Here is my code:
plot_positions = dash_table.DataTable(
id='Positions',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict('records'),
)
st.dataframe(plot_positions)
How can I/what's the proper way to display a DataTable object on Streamlit?
I am using dash instead of plotly.go.Table because conditional formatting on with dash DataTables is easier (something I need for my project).

Consistent update dash page across connections

I'm making a multi-page dash application that I plan to host on a server using Gunicorn and Nginx. It will access a PostgreSQL database on an external server over the network.
The data on one of the pages is obtained by a query from the database and should be updated every 30 seconds. I use to update the #callback through the dcc.Interval.
My code (simplified version):
from dash import Dash, html, dash_table, dcc, Input, Output, callback
import dash_bootstrap_components as dbc
from flask import Flask
import pandas as pd
from random import random
server = Flask(__name__)
app = Dash(__name__, server=server, suppress_callback_exceptions=True, external_stylesheets=[dbc.themes.BOOTSTRAP])
app.layout = html.Div([
dcc.Interval(
id='interval-component-time',
interval=1000,
n_intervals=0
),
html.Br(),
html.H6(id='time_update'),
dcc.Interval(
id='interval-component-table',
interval=1/2*60000,
n_intervals=0
),
html.Br(),
html.H6(id='table_update')
])
#callback(
Output('time_update', 'children'),
Input('interval-component-time', 'n_intervals')
)
def time_update(n_intervals):
time_show = 30
text = "Next update in {} sec".format(time_show - (n_intervals % 30))
return text
#callback(
Output('table_update', 'children'),
Input('interval-component-table', 'n_intervals')
)
def data_update(n_intervals):
# here in a separate file a query is made to the database and a dataframe is returned
# now here is a simplified receipt df
col = ["Col1", "Col2", "Col3"]
data = [[random(), random(), random()]]
df = pd.DataFrame(data, columns=col)
return dash_table.DataTable(df.to_dict('records'),
style_cell={'text-align': 'center', 'margin-bottom': '0'},
style_table={'width':'500px'})
if __name__ == '__main__':
server.run(port=5000, debug=True)
Locally, everything works fine for me, the load on the database is small, one such request loads 1 out of 8 processors by 30% for 3 seconds.
But, if you open my application in several browser windows, then the same data is displayed on two pages by two queries to the database at different times, that is, the load doubles. I am worried that when connecting more than 10 people, my server with the database will not withstand / will freeze heavily, and the database on it should work without delay and not fall.
Question:
Is it possible to make page refresh the same for different connections? That is, so that the data is updated at the same time for different users and only with the help of one query to the database.
I studied everything about the callback in the documentation and did not find an answer.
Solution
Thanks for the advice, #Epsi95! I studied page Dash Performance and added this to my code:
cache = Cache(app.server, config={
'CACHE_TYPE': 'filesystem',
'CACHE_DIR': 'cache-directory',
'CACHE_THRESHOLD': 50
})
#cache.memoize(timeout=30)
def query_data():
# here I make a query to the database and save the result in a dataframe
return df
def dataframe():
df = query_data()
return df
And in the #callback function I make a call to the dataframe() function.
Everything works the way I needed it. Thank you!

Dash Sort editable table, but hide sort options from users

I have a dash table. Table allows edit. I want to sort the table by column, so that if user input data, the table is resorted right away. I achieve this like on the page https://dash.plotly.com/datatable/callbacks. The sort is already set when the page loads. I got stuck on the last step, where I want to hide the sort option from user. Is that possible?
Example on the image. I want to delete the arrows marked yellow, but keep sort by column 'pop'.
edited code example from https://dash.plotly.com/datatable/callbacks:
import dash
from dash.dependencies import Input, Output
import dash_table
import pandas as pd
app = dash.Dash(__name__)
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminder2007.csv')
PAGE_SIZE = 5
app.layout = dash_table.DataTable(
id='table-multicol-sorting',
columns=[
{"name": i, "id": i} for i in sorted(df.columns)
],
data=df.to_dict('records'),
page_size=PAGE_SIZE,
sort_action='native',
sort_mode='multi',
sort_as_null=['', 'No'],
sort_by=[{'column_id': 'pop', 'direction': 'asc'}],
editable=True,
)
if __name__ == '__main__':
app.run_server(debug=True)
You can target the sort element and hide it using css like this:
span.column-header--sort {
display: none;
}
So you can put that code in a css file in your assets directory for example. See the documentation here for more information about ways to include styles in a dash app.
I am able to do it by sort_action='none' in Dash v1.16.2

Python Dash DataTable: row selection not working

When I set row_selectable as 'multi' in a DataTable, I would expect an extra column on the very left with checkboxes to select arbitrary rows. However, when I do it, that column does not contain any checkboxes. Therefore, row selection is not possible.
import dash
import dash_table
import pandas as pd
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/solar.csv')
app = dash.Dash(__name__)
app.layout = dash_table.DataTable(
id='table',
columns=[{"name": i, "id": i} for i in df.columns],
data=df.to_dict("rows"),
row_selectable='multi'
)
if __name__ == '__main__':
app.run_server(debug=True)
row_selectable='single' results in the same output. I am using Python 3.6.8, dash 0.39.0, dash-table 3.6.0
Can somebody help, please?
Please install the latest dash
pip install dash==1.12.0
This will fix the issue.

Categories