Search code examples
pythonplotlyplotly-dash

plotly dash layout update


app = Dash(__name__)

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

@app.callback(
    Output('page-content', 'children'),
    Input('url', 'search')
)

def url_check(search):
    project_key = re.search('project_key=(\w+)&', search).group(1)
    if project_key == 'U9sD0DItDJ0479kiFPG8':
        layout = html.Div([
                dcc.Dropdown(options=['bar', 'pie'], id='dropdown', multi=False, value='bar',
                             placeholder='Select graph type'),
                html.Div(id='page-content'),
        ])
        return layout
    else:
        layout = html.Div([
            html.Div('실패')
        ])



if __name__ == '__main__':

    app.run_server(debug=True)

this is my code when i receive project_key in URL if url match my project_key then want to show dropdown, and graph But if not match my project_key just show 404error How to do that??


Solution

  • There are many ways to do this. You can try something like this. You can add a condition to check if the project_key passed in the URL matches the desired key, and if it doesn't, you can redirect the user to a 404 error page.

        @app.callback(
        Output('url', 'pathname'),
        Input('url', 'search')
    )
    def url_check(search):
        project_key = re.search('project_key=(\w+)&', search).group(1)
        if project_key == 'U9sD0DItDJ0479kiFPG8':
            return None
        else:
            # Redirect to 404 error page
            return '/404'
    
    @app.callback(Output('page-content', 'children'), [Input('url', 'pathname')])
    def display_page(pathname):
        if pathname == '/404':
            return html.Div([html.H1('404: Page not found')])
        else:
            layout = html.Div([
                    dcc.Dropdown(options=['bar', 'pie'], id='dropdown', multi=False, value='bar',
                                 placeholder='Select graph type'),
                    html.Div(id='page-content'),
            ])
            return layout