I also want to know about another question,
I am creating a dashboard that is taken data from the MongoDB database. in my front end side, I show the previous day data and when I used date-picker its show those day data tables now I want to add another feature is that columns name “Driver Name” convert into a hyperlink and when user click on this hyperlink then it’s getting data from MongoDB database for last 30 days for a particular driver.
please help me out for this
code for above pic
from datetime import datetime as dt
import dash
from dash.dependencies import Input, Output, State
import dash_html_components as html
import dash_core_components as dcc
import re
import dash_table
Import Libraries
import pdb
import json
import datetime
import dateutil.parser
from datetime import datetime
from dateutil import tz
import pytz
import pandas as pd
import numpy as np
import pymongo
from pymongo import MongoClient
from datetime import timedelta
import pandas.io.sql as sqlio
import pdb
import datetime
import dateutil.parser
from datetime import datetime
from dateutil import tz
import pytz
import pandas as pd
import numpy as np
from pymongo import MongoClient
from datetime import timedelta
external_stylesheets = [‘https://codepen.io/chriddyp/pen/bWLwgP.css’]
app = dash.Dash(name, external_stylesheets=external_stylesheets)
app.layout = html.Div([
# this div part for front-end header view
html.Div(
[
# This Div part responsibale for the safehur logo
html.Div(
[
html.Img(
src=app.get_asset_url(“safehur.png”),
id=“plotly-image”,
style={
“height”: “60px”,
“width”: “auto”,
“margin-bottom”: “25px”,
},
)
],
className=“one-third column”,
),
html.Div(
[
#html.Div(
# [
html.H3(
“Intello-transpo”,
style={“margin-bottom”: “0px”},
),
html.H5(
“DDR Automated Report”, style={“margin-top”: “0px”}
),
#]
#)
],
className=“one-half column”,
id=“title”,
),
html.Div(
[
html.A(
html.Button(“Learn More”, id=“learn-more-button”),
href=“http://www.intello-transpo.com/”,
)
],
className=“one-third column”,
id=“button”,
),
],
id=“header”,
className=“row flex-display”,
style={“margin-bottom”: “25px”},
),
dcc.DatePickerSingle(
id=‘my-date-picker-single’,
min_date_allowed=dt(2020, 1, 18),
max_date_allowed=dt.date(dt.now()),
initial_visible_month=dt.date(dt.now()),
placeholder=‘Select a date’,
display_format=‘DD/MM/YYYY’
),
html.Button(id=‘submit-button’, n_clicks=0, children=‘Submit’,),
html.Div(id=‘output-container-date-picker-single’)
])
@app.callback(
Output(‘output-container-date-picker-single’,‘children’),
[Input(‘my-date-picker-single’, ‘date’)])
[
Input('submit-button', 'n_clicks'),
],
[
State('my-date-picker-single', 'date'),
])
def table_link(dataframe,link_column,link_format,**kwargs):
“”"note that this function should only be used if the table needs hyperlinking otherwise
use the table_div function already existing.
Args:
dataframe (pandas.DataFrame): The representative dateframe we want to make a table that somehow needs hyperlinking
in a cell.
link_column (str): name of the column that needs hyperlinks.
link_format (lambda): lambda function that parses **kwargs and returns a str
note that we need to sent make sure all values that we need are sent in kwargs
if you need to use the cell content use the paramater value. (e.g. lambda value,x:f'{x}/{value}')
Returns:
HTML table this the dataframe represented and the linkin in the column needed
"""
rows = []
for i in range(len(dataframe)):
row = []
for col in dataframe.columns:
value = dataframe.iloc[i][col]
kwargs['value'] = value
if col == link_column:
cell = html.Td(html.A(value, target='_blank',href=link_format(**kwargs)))
else:
cell = html.Td(children=value)
row.append(cell)
rows.append(html.Tr(row))
return html.Table(
# Header
[html.Tr([html.Th(col.title()) for col in dataframe.columns])] +
rows,className='table',
)
def update_output(n_clicks, date):
if date is not None and n_clicks>0:
date = dt.strptime(re.split('T| ', date)[0], '%Y-%m-%d')
#date_string = date.strftime('%B %d, %Y')
#date = date.dt.date
local_server = pymongo.MongoClient("mongodb://localhost:27017/")
db_local_server = local_server["safehur_production_success"]
collection_ddr_client = db_local_server["DDR_new3"]
field_list = [u'Organization ID', u'Organization Name',
u'Driver Name', u'IMEI', u'Vehicle Number',
u'Date', u'Last Moved Date', u'gps_total_count',
u'GPS Locked %', u'LIDAR Issue %', u'LIDAR Obstruction %', u'Temp Issue %', u'IMU Issue %',
u'GPS Ant OK %', u'gps_ant_open_count',
u'Total Distance (Km)', u'Total Minutes', u'Total Success Packets', u'Total Corrupt Packets',
u'Total Packets',
u'Packet Rate (per min)','No Restart Devies']
ddr_query = {"Date": {"$eq": date}}
fields = {field: 1 for field in field_list}
ddr_docs = collection_ddr_client.find(ddr_query, fields)
df = pd.DataFrame(list(ddr_docs))
# print (df.head())
# df = df.drop("_id", axis=1)
df['#'] = df.index
#df['Last Moved Date'] = df['Last Moved Date'].dt.date
df['Date'] = df['Date'].dt.date
df = df[
["#", u'Organization ID', u'Organization Name',
u'Driver Name', u'IMEI', u'Vehicle Number',
u'Date', u'Last Moved Date', u'gps_total_count',
u'GPS Locked %', u'LIDAR Issue %', u'LIDAR Obstruction %', u'Temp Issue %', u'IMU Issue %',
u'GPS Ant OK %', u'gps_ant_open_count',
u'Total Distance (Km)', u'Total Minutes', u'Total Success Packets', u'Total Corrupt Packets',
u'Total Packets',
u'Packet Rate (per min)','No Restart Devies']]
# this is function call for the hyper link of Driver Name
return dash_table.DataTable(
id='datatable-row-ids',
columns=[{"name": i, "id": i, "selectable": True} for i in df.columns],
data=df.to_dict('records'),
sort_action='native',
filter_action='native',
sort_mode='multi',
# row_selectable='multi',
# condition for highlighting cell whcih have issue
style_data_conditional=[
{
'if': {
'filter_query': '{gps_total_count} != 0 && {LIDAR Obstruction %} > 10 && {LIDAR Obstruction %} <= 100',
'column_id': 'LIDAR Obstruction %'
},
'backgroundColor': 'red',
'color': 'white'
},
{
'if': {
'filter_query': '{gps_total_count} != 0 && {GPS Locked %} >= 0 && {GPS Locked %} < 50',
'column_id': 'GPS Locked %'
},
'backgroundColor': 'red',
'color': 'white'
},
{
'if': {
'filter_query': '{gps_total_count} != 0 && {GPS Ant OK %} >= 0 && {GPS Ant OK %} < 60',
'column_id': 'GPS Ant OK %'
},
'backgroundColor': 'red',
'color': 'white'
},
{
'if': {
'filter_query': '{gps_total_count} != 0 && {Temp Issue %} > 0 && {Temp Issue %} <= 100',
'column_id': 'Temp Issue %'
},
'backgroundColor': 'red',
'color': 'white'
},
{
'if': {
'filter_query': '{gps_total_count} != 0 && {IMU Issue %} > 0 && {IMU Issue %} <= 100',
'column_id': 'IMU Issue %'
},
'backgroundColor': 'red',
'color': 'white'
},
{
'if': {
'filter_query': '{gps_total_count} != 0 && {LIDAR Issue %} > 0 && {LIDAR Issue %} <= 100',
'column_id': 'LIDAR Issue %'
},
'backgroundColor': 'red',
'color': 'white'
},
],
)
else:
date_1 = datetime.utcnow()
# print ("Datetime Now UTC: ", date)
date_1 = date_1.replace(hour=0, minute=0, second=0, microsecond=0)
# print ("Datetime Now UTC Start of Day: ", date)
date_1 = date_1 - timedelta(hours=48, minutes=0)
# print ("Last Day Start Time (-24 Hrs) : ", date)
local_server = pymongo.MongoClient("mongodb://localhost:27017/")
db_local_server = local_server["safehur_production_success"]
collection_ddr_client = db_local_server["DDR_new3"]
field_list = [u'Organization ID', u'Organization Name',
u'Driver Name', u'IMEI', u'Vehicle Number',
u'Date', u'Last Moved Date', u'gps_total_count',
u'GPS Locked %', u'LIDAR Issue %', u'LIDAR Obstruction %', u'Temp Issue %', u'IMU Issue %',
u'GPS Ant OK %', u'gps_ant_open_count',
u'Total Distance (Km)', u'Total Minutes', u'Total Success Packets', u'Total Corrupt Packets',
u'Total Packets',
u'Packet Rate (per min)','No Restart Devies']
ddr_query = {"Date": {"$gte": date_1}}
fields = {field: 1 for field in field_list}
ddr_docs = collection_ddr_client.find(ddr_query, fields)
df = pd.DataFrame(list(ddr_docs))
# print (df.head())
# df = df.drop("_id", axis=1)
df['#'] = df.index
df['Last Moved Date'] = df['Last Moved Date'].dt.date
df['Date'] = df['Date'].dt.date
df = df[
["#", u'Organization ID', u'Organization Name',
u'Driver Name', u'IMEI', u'Vehicle Number',
u'Date', u'Last Moved Date', u'gps_total_count',
u'GPS Locked %', u'LIDAR Issue %', u'LIDAR Obstruction %', u'Temp Issue %', u'IMU Issue %',
u'GPS Ant OK %', u'gps_ant_open_count',
u'Total Distance (Km)', u'Total Minutes', u'Total Success Packets', u'Total Corrupt Packets',
u'Total Packets',
u'Packet Rate (per min)','No Restart Devies']]
# this is function call for the hyper link of Driver Name
return dash_table.DataTable(
id='datatable-row-ids',
columns=[{"name": i, "id": i, "selectable": True} for i in df.columns],
data=df.to_dict('records'),
sort_action='native',
filter_action='native',
sort_mode='multi',
# row_selectable='multi',
# condition for highlighting cell whcih have issue
style_data_conditional=[
{
'if': {
'filter_query': '{gps_total_count} != 0 && {LIDAR Obstruction %} > 10 && {LIDAR Obstruction %} <= 100',
'column_id': 'LIDAR Obstruction %'
},
'backgroundColor': 'red',
'color': 'white'
},
{
'if': {
'filter_query': '{gps_total_count} != 0 && {GPS Locked %} >= 0 && {GPS Locked %} < 50',
'column_id': 'GPS Locked %'
},
'backgroundColor': 'red',
'color': 'white'
},
{
'if': {
'filter_query': '{gps_total_count} != 0 && {GPS Ant OK %} >= 0 && {GPS Ant OK %} < 60',
'column_id': 'GPS Ant OK %'
},
'backgroundColor': 'red',
'color': 'white'
},
{
'if': {
'filter_query': '{gps_total_count} != 0 && {Temp Issue %} > 0 && {Temp Issue %} <= 100',
'column_id': 'Temp Issue %'
},
'backgroundColor': 'red',
'color': 'white'
},
{
'if': {
'filter_query': '{gps_total_count} != 0 && {IMU Issue %} > 0 && {IMU Issue %} <= 100',
'column_id': 'IMU Issue %'
},
'backgroundColor': 'red',
'color': 'white'
},
{
'if': {
'filter_query': '{gps_total_count} != 0 && {LIDAR Issue %} > 0 && {LIDAR Issue %} <= 100',
'column_id': 'LIDAR Issue %'
},
'backgroundColor': 'red',
'color': 'white'
},
],
)
if name == ‘main’:
app.run_server(debug=True)