Skip to content

Instantly share code, notes, and snippets.

@eddy-geek
Last active March 10, 2022 19:01
Show Gist options
  • Select an option

  • Save eddy-geek/73c8f73c089b0f998a49541b15a694b1 to your computer and use it in GitHub Desktop.

Select an option

Save eddy-geek/73c8f73c089b0f998a49541b15a694b1 to your computer and use it in GitHub Desktop.

Revisions

  1. eddy-geek revised this gist Mar 10, 2022. 1 changed file with 5 additions and 0 deletions.
    5 changes: 5 additions & 0 deletions dash_state_demo_datepicker.py
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,8 @@
    # Copyright (C) 2022 by Edward O.
    # Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without l> imitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
    # The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
    # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE

    import ast
    import re

  2. eddy-geek revised this gist Mar 22, 2020. 1 changed file with 21 additions and 7 deletions.
    28 changes: 21 additions & 7 deletions dash_state_demo_datepicker.py
    Original file line number Diff line number Diff line change
    @@ -1,6 +1,8 @@
    import ast
    import re

    import flask

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    @@ -9,15 +11,13 @@

    app = dash.Dash()

    app.config.suppress_callback_exceptions = True


    app.layout = html.Div([
    url_bar_and_content_div = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Div(id='page-layout')
    ])



    def apply_default_value(params):
    """
    :param params: the state decoded from url
    @@ -32,7 +32,9 @@ def apply_value(*args, **kwargs):
    return wrapper


    def build_layout(params):
    def page_layout(params=None):

    params = params or {}
    layout = [
    html.H2('URL State demo', id='state'),
    apply_default_value(params)(dcc.DatePickerRange)(
    @@ -61,6 +63,19 @@ def build_layout(params):
    return layout


    def app_layout():
    if flask.has_request_context(): # for real
    return url_bar_and_content_div
    # validation only
    return html.Div([
    url_bar_and_content_div,
    *page_layout()
    ])


    app.layout = app_layout


    ID_PARAM_SEP = '::'


    @@ -76,7 +91,6 @@ def parse_state(url):
    id, param = key, 'value'
    state.setdefault(id, {})[param] = ast.literal_eval(value)

    print('state', state)
    return state


    @@ -86,7 +100,7 @@ def page_load(href):
    if not href:
    return []
    state = parse_state(href)
    return build_layout(state)
    return page_layout(state)


    component_ids = {
  3. eddy-geek revised this gist Mar 22, 2020. 1 changed file with 0 additions and 2 deletions.
    2 changes: 0 additions & 2 deletions dash_state_demo_datepicker.py
    Original file line number Diff line number Diff line change
    @@ -68,8 +68,6 @@ def parse_state(url):
    parse_result = urlparse(url)
    query_string = parse_qsl(parse_result.query)

    print(query_string)

    state = {}
    for key, value in query_string:
    if ID_PARAM_SEP in key:
  4. eddy-geek created this gist Mar 22, 2020.
    124 changes: 124 additions & 0 deletions dash_state_demo_datepicker.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,124 @@
    import ast
    import re

    import dash
    import dash_core_components as dcc
    import dash_html_components as html
    from urllib.parse import urlparse, parse_qsl, urlencode, quote
    from dash.dependencies import Input, Output

    app = dash.Dash()

    app.config.suppress_callback_exceptions = True


    app.layout = html.Div([
    dcc.Location(id='url', refresh=False),
    html.Div(id='page-layout')
    ])


    def apply_default_value(params):
    """
    :param params: the state decoded from url
    """
    def wrapper(func):
    def apply_value(*args, **kwargs):
    if 'id' in kwargs and kwargs['id'] in params:
    param_key_dict = params[kwargs['id']]
    kwargs.update(param_key_dict)
    return func(*args, **kwargs)
    return apply_value
    return wrapper


    def build_layout(params):
    layout = [
    html.H2('URL State demo', id='state'),
    apply_default_value(params)(dcc.DatePickerRange)(
    id='picker',
    ),
    apply_default_value(params)(dcc.Dropdown)(
    id='dropdown',
    options=[{'label': i, 'value': i} for i in ['LA', 'NYC', 'MTL']],
    value='LA'
    ),
    apply_default_value(params)(dcc.Input)(
    id='input',
    placeholder='Enter a value...',
    value=''
    ),
    apply_default_value(params)(dcc.Slider)(
    id='slider',
    min=0,
    max=9,
    marks={i: 'Label {}'.format(i) for i in range(10)},
    value=5,
    ),
    html.Br(),
    ]

    return layout


    ID_PARAM_SEP = '::'


    def parse_state(url):
    parse_result = urlparse(url)
    query_string = parse_qsl(parse_result.query)

    print(query_string)

    state = {}
    for key, value in query_string:
    if ID_PARAM_SEP in key:
    id, param = key.split(ID_PARAM_SEP)
    else:
    id, param = key, 'value'
    state.setdefault(id, {})[param] = ast.literal_eval(value)

    print('state', state)
    return state


    @app.callback(Output('page-layout', 'children'),
    inputs=[Input('url', 'href')])
    def page_load(href):
    if not href:
    return []
    state = parse_state(href)
    return build_layout(state)


    component_ids = {
    'picker': ['start_date', 'end_date'],
    'dropdown': ['value'],
    'input': ['value'],
    'slider': ['value'],
    }


    def param_string(id, p):
    return id if p == 'value' else id + ID_PARAM_SEP + p


    RE_SINGLE_QUOTED = re.compile("^'|'$")
    def myrepr(o):
    """Optional but chrome URL bar hates "'" """
    return RE_SINGLE_QUOTED.sub('"', repr(o))


    @app.callback(Output('url', 'search'),
    inputs=[Input(id, p) for id, param in component_ids.items() for p in param])
    def update_url_state(*values):
    """Updates URL from component values."""

    keys = [param_string(id, p) for id, param in component_ids.items() for p in param]
    state = dict(zip(keys, map(myrepr, values)))
    params = urlencode(state, safe="%/:?~#+!$,;'@()*[]\"", quote_via=quote)
    return f'?{params}'


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