Hi guys,
I tried this example:dcc.Location refresh=False doesn't fire the callback for derived URL properties · Issue #925 · plotly/dash-core-components · GitHub
It works well.
However, when I integrate dash with flask, the url doesn’t update again and doesn’t save.
here is my code. I’m a beginner in Dash and Flask, please help me
Thank you.
webapp/app/app4/layout.py
from dash_extensions.enrich import Dash
from dash_extensions.enrich import Dash, ServersideOutput ,Output, Input, State, Trigger
from flask import Flask
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import urllib
import pandas as pd
from datetime import date
def plotly_sample_app():
layout1 = html.Div([
dcc.Location(id='url', refresh=False),
html.Div(id='content1'),
html.Div(id='content2'),
html.Div(id='content3'),
dcc.Graph(id='graph-with-slider'),
])
return layout1
layout = html.Div(
id='app_4_page_layout',
children=[
# shared_dash_nav_links(),
plotly_sample_app(),
# other layout functions can go here.
]
)
webapp/app/app4/callbacks.py
from dash_extensions.enrich import Dash
from dash_extensions.enrich import Dash, ServersideOutput ,Output, Input, State, Trigger
from flask import Flask
import dash_core_components as dcc
import dash_html_components as html
# from dash.dependencies import Input, Output,State
import plotly.express as px
import urllib
import pandas as pd
from datetime import date
global df
df = pd.read_csv('https://raw.githubusercontent.com/plotly/datasets/master/gapminderDataFiveYear.csv')
def register_callbacks(app):
@app.callback(
Output('output', 'children'),
Input('url', 'href'),
State('url', 'pathname'),
State('url', 'search'))
def update_output_based_off_url(href, pathname, search):
return html.Div([
html.B('Callback inputs tell me that:'),
html.Pre(f'href={href}\npathname={pathname}\nsearch={search}')
])
@app.callback(Output('content1', 'children'), Input('url', 'href'))
def display_page1(href):
o = list(urllib.parse.urlparse(href))
q = dict(urllib.parse.parse_qsl(o[4]))
pathname = o[2]
if(q =={}):
value = 1952
value_ = 'Asia'
else:
value = int(q['site'])
value_ = q['dum']
return html.Div([
dcc.Slider(
id='year-slider',
min=df['year'].min(),
max=df['year'].max(),
value= value,
marks={str(year): str(year) for year in df['year'].unique()},
step=None
),
])
@app.callback(Output('content2', 'children'), Input('url', 'href'))
def display_page2(href):
o = list(urllib.parse.urlparse(href))
q = dict(urllib.parse.parse_qsl(o[4]))
pathname = o[2]
if(q =={}):
value_ = 'Asia'
else:
value_ = q['dum']
return html.Div([
dcc.Dropdown(id='yield_handler_select',
options=[{'label':name, 'value':name} for name in df['continent'].unique()],
value = value_,
style=dict(width='40%',verticalAlign="middle"), ),
])
@app.callback(Output('content3', 'children'), Input('url', 'href'))
def display_page3(href):
o = list(urllib.parse.urlparse(href))
q = dict(urllib.parse.parse_qsl(o[4]))
pathname = o[2]
if(q =={} or q['start']=='None' or q['start']==None):
value_ = date(2021, 8, 9)
else:
value_ = q['start']
print('value',value_)
return html.Div([
html.Div(id='output'),
dcc.DatePickerSingle(
id='start',
date=value_,
),
])
@app.callback(
Output('graph-with-slider', 'figure'),
Input('start', 'value'),
Input('year-slider', 'value'),
Input('yield_handler_select','value'),
State('url', 'href')
)
def update_figure(start,selected_year,continent,url):
print(selected_year)
filtered_df = df[df.year == selected_year]
filtered_df = filtered_df[filtered_df.continent==continent]
fig = px.scatter(filtered_df, x="gdpPercap", y="lifeExp",
size="pop", color="continent", hover_name="country",
log_x=True, size_max=55)
fig.update_layout(transition_duration=500)
return fig
@app.callback(
Output('url', 'href'),
Input('start', 'date'),
Input('year-slider', 'value'),
Input('yield_handler_select','value'),
State('url', 'href'))
def update_pathname(start,site,dum,href):
# print('trigger: ',len(dash.callback_context.triggered))
# if len(dash.callback_context.triggered) == 3:
# return dash.no_update
o = urllib.parse.urlparse(href)
print('o1',o)
o = o._replace(path='/report/')
print('o1',o)
q = dict(urllib.parse.parse_qsl(o.query))
q['site'] = site
q['dum']=dum
q['start']=start
print('start',start)
query_string = urllib.parse.urlencode(q)
o = o._replace(query=query_string)
a= o.geturl()
print(a)
# return return app.config["url_base_pathname"] + "pathname"
return o.geturl()
webapp/app/init.py
from flask import Flask
from flask.helpers import get_root_path
# from dash import Dash
from dash_extensions.enrich import Dash
from os import getpid
import os,sys
class Config:
# user configurations
flask_debug = False
dash_debug = False
dash_auto_reload = False
SECRET_KEY = 'askjdfkajsdfksdf'
def create_app(dash_debug, dash_auto_reload):
server = Flask(__name__,template_folder = 'templates',static_folder='static')
server.config.from_object(Config)
from sltanalysis.webapp.app.app4.layout import layout as app_4_layout
from sltanalysis.webapp.app.app4.callbacks import register_callbacks as app_4_callbacks
register_dash_app(
flask_server=server,
title='App 4',
base_pathname='app_4_raw_dash',
layout=app_4_layout,
register_callbacks_funcs=[app_4_callbacks],
dash_debug=dash_debug,
dash_auto_reload=dash_auto_reload
)
register_blueprints(server)
return server
def register_dash_app(flask_server, title, base_pathname, layout, register_callbacks_funcs, dash_debug, dash_auto_reload):
# Meta tags for viewport responsiveness
meta_viewport = {"name": "viewport", "content": "width=device-width, initial-scale=1, shrink-to-fit=no"}
my_dash_app = Dash(
__name__,
server=flask_server,
url_base_pathname=f'/{base_pathname}/',
assets_folder=get_root_path(__name__) + '/static/',
external_stylesheets=['/static/s1.css','/static/app_style.css','/static/styles.css'],
suppress_callback_exceptions=True,
)
with flask_server.app_context():
my_dash_app.title = title
my_dash_app.layout = layout
my_dash_app.css.config.serve_locally = True
my_dash_app.enable_dev_tools(debug=dash_debug, dev_tools_hot_reload=dash_auto_reload)
for call_back_func in register_callbacks_funcs:
call_back_func(my_dash_app)
def register_blueprints(server):
from sltanalysis.webapp.app.routes import server_bp
server.register_blueprint(server_bp)
webapp/app/routes.py
from flask import Blueprint, render_template
from flask import send_from_directory
import jinja2
import os,sys
import sys
server_bp = Blueprint('web', __name__,template_folder = 'templates',static_folder='static')
@server_bp.route('/')
def index():
return render_template("base.html", title='Home Page')
@server_bp.route('/tmp/')
def app_4_template():
return render_template('dash.html', dash_url='/app_4_raw_dash/')
webapp/run.py
from sltanalysis.webapp.app import create_app
server = create_app(dash_debug=False, dash_auto_reload=False)
def start():
server.run(host='0.0.0.0', port=8000, threaded=True)
if __name__ == "__main__":
start()